-- Copyright (c) 2025 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'

TestCanbus = {}

local function get_pbit(val)
    return 1 << val
end

function TestCanbus:test_update_pre_health_event()
    local canbus = require 'device_tree.adapters.power_mgmt.protocol.monitor.canbus'({})
    local health_event = {
        event = 0,
        output_voltage_fault = 0,
        output_current_fault = 0,
        temper_fault = 0,
        input_voltage_fault =0
    }
    local ok, result = pcall(function()
        return canbus.update_pre_health_event(canbus, health_event, nil)
    end)
    lu.assertEquals(ok, true)
    lu.assertEquals(health_event.event, result.event)
    lu.assertEquals(health_event.output_voltage_fault, result.output_voltage_fault)
    lu.assertEquals(health_event.output_current_fault, result.output_current_fault)
    lu.assertEquals(health_event.temper_fault, result.temper_fault)
    lu.assertEquals(health_event.input_voltage_fault, result.input_voltage_fault)

    -- 模拟输入电压偏低
    local pre_alarm_status = get_pbit(1)
    ok, result = pcall(function()
        return canbus.update_pre_health_event(canbus, health_event, pre_alarm_status)
    end)
    lu.assertEquals(ok, true)
    lu.assertEquals(result.input_voltage_fault, get_pbit(5))
    health_event.input_voltage_fault = 0

    -- 模拟输入电压偏高
    pre_alarm_status = get_pbit(0)
    ok, result = pcall(function()
        return canbus.update_pre_health_event(canbus, health_event, pre_alarm_status)
    end)
    lu.assertEquals(ok, true)
    lu.assertEquals(result.input_voltage_fault, get_pbit(6))
    health_event.input_voltage_fault = 0

    -- 模拟温度偏高
    pre_alarm_status = get_pbit(16)
    ok, result = pcall(function()
        return canbus.update_pre_health_event(canbus, health_event, pre_alarm_status)
    end)
    lu.assertEquals(ok, true)
    lu.assertEquals(result.temper_fault, get_pbit(6))
    lu.assertEquals(result.event, get_pbit(3))
end
