-- 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 c_network_port = require 'device.class.network_port'
local c_object_manage = require 'mc.orm.object_manage'
local npu_imu_cmd = require 'npu.hdk_cmd'
local test_utils = require 'test_utils'
local class_mgnt = require "mc.class_mgnt"
local fructl = require 'infrastructure.fructl'
skynet = require 'skynet'
local c_network_port = require 'device.class.network_port'
local context = require 'mc.context'
local client = require 'network_adapter.client'
local vos = require 'utils.vos'
local c_optical_module = require 'device.class.optical_module'

TEST_network_port = {}

local INVALID_DATA_STRING<const> = 'N/A'

local mock_imu_info = {
    received = 'test',
    transmitted = 'test_transmitted',
    dropped = 'test_dropped',
    mac_addr = 'test_mac_addr',
    rx_fcs_err_pkt_num = 'test_rx_fcs_err_pkt_num',
    subnet_mask = 'test_subnet_mask',
    gateway = 'test_gateway',
    ip_addr = 'test_ipaddr',
    link_up_cnt = 1,
    link_down_cnt = 2,
    link_up_timestamp = {3},
    link_down_timestamp = {0,44}
}

local mock_imu_hccs_info = {
    {
        macro_id = 1,
        health_status = 1,
        lane_mode = {},
        link_lane_list = {},
        link_speed = {},
        tx_packets = {},
        tx_bytes = {},
        rx_packets = {},
        rx_bytes = {},
        retry_count = {},
        error_count = {},
        first_error_lane = 2,
        snr = {0, 2, 4, 6},
        half_height = {0, 1, 2, 3}
    }
}

local function mock_get_info_from_imu(id, power_on)
    return mock_imu_info
end

local function mock_get_hccs_info_from_imu(id, power_on)
    return mock_imu_hccs_info
end

local function mock_create_ipv4_addr(Object, SystemID, ID1, ID2, ID3, prop_setting_cb)
    local path = '/bmc/kepler/Systems/' .. SystemID .. '/NetworkAdapters/' .. ID1 .. '/Ports/' ..
                ID2 .. '/IPv4Addresses/' .. ID3 .. ''
    local obj = {path = path}
    prop_setting_cb(obj)
    return obj
end

local function mock_get_instance()
    return {
        app = {
            CreateIPv4Address = mock_create_ipv4_addr
        }
    }
end

local function mock_get_postion()
    return 'test_postion'
end

local function mock_class_mgnt(...)
    return {
        remove = function(...)
            return nil
        end
    }
end

local function mock_get_power_status(...)
    return 'OFF'
end

local mock_network_port = {
    NpuID = 1,
    per_module_log_cnt = 0,
    record_flag = 0,
    link_up_cnt = 0,
    link_down_cnt = 0,
    link_up_timestamp = {},
    link_down_timestamp = {},
    npu_port_log_buffer = {},
    PortID = 1,
    RXFrames = 'test',
    TXFrames = 'test',
    PacketsDropped = 'test',
    MACAddress = 'test',
    RXFCSErrors = 'test',
    npu_ipv4_obj = false,
    npu_ipv4_info = {
        Address = INVALID_DATA_STRING,
        SubnetMask = INVALID_DATA_STRING,
        Gateway = INVALID_DATA_STRING
    },
    get_position = mock_get_postion,
    hccs_info = {
        npu_id = 1,
        health_status = 0,
        lane_mode = {},
        link_lane_list = {},
        link_speed = {},
        tx_packets = {},
        tx_bytes = {},
        rx_packets = {},
        rx_bytes = {},
        retry_count = {},
        error_count = {},
        first_error_lane = 255,
        snr_max = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0},
            {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
        snr_min = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0},
            {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
        half_height_max = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0},
            {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
        half_height_min = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0},
            {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}
    },
    clear_npu_port_basic_info = function(...)
        return nil
    end,
    get_npu_port_basic_info = function()
        return 'str' + 1
    end,
    clear_hccs_info = function()
        return
    end,
    update_npu_port_basic_info = function()
        return
    end,
    update_npu_port_hccs_info = function()
        return
    end,
    npu_port_log_collect_record = function()
        return
    end,
    sleep_ms = function(...)

    end
}

local get_info_from_imu = npu_imu_cmd.get_info_from_imu
local get_hccs_info_from_imu = npu_imu_cmd.get_hccs_info_from_imu
local get_instance = c_object_manage.get_instance
local get_power_status = fructl.get_power_status

function TEST_network_port:setUp()
    npu_imu_cmd.get_info_from_imu = mock_get_info_from_imu
    npu_imu_cmd.get_hccs_info_from_imu = mock_get_hccs_info_from_imu
    c_object_manage.get_instance = mock_get_instance
    fructl.get_power_status = mock_get_power_status
end

function TEST_network_port:tearDown()
    npu_imu_cmd.get_info_from_imu = get_info_from_imu
    npu_imu_cmd.get_hccs_info_from_imu = get_hccs_info_from_imu
    c_object_manage.get_instance = get_instance
    fructl.get_power_status = get_power_status
end

local test_data = {
    LinkStatus = 'N/A',
    NetworkAdapterId = 0,
    PortID = 0,
    SpeedMbps = 0,
    AutoSpeedNegotiation = false,
    FullDuplex = false
}
-- 测试更新链接状态
function TEST_network_port:test_update_ncsi_link_status()
    local origin_smbus_schedulers = c_network_port.smbus_schedulers
    local origin_get_properties_res = c_network_port.get_properties_res
    c_network_port.t_port_prop_without_bma = {}
    c_network_port.schedulers = {}
    c_network_port.smbus_schedulers = {}
    c_network_port.get_properties_res = {}
    c_network_port.ncsi_config_obj = {
        LinkStatus = function()
            return {
                on_data_change = {
                    on = function(self, func)
                        func(test_data)
                        c_network_port.ncsi_get_linkstatus_retry_count = 2
                    end
                },
                on_error = {
                    on = function(self, func)
                        func()
                    end
                },
                start = function()
                end
            }
        end
    }
    c_network_port:update_ncsi_link_status()
    lu.assertIsFalse(c_network_port.AutoSpeedNegotiation)
    lu.assertIsFalse(c_network_port.FullDuplex)
    lu.assertEquals(c_network_port.LinkStatus, test_data.LinkStatus)
    lu.assertEquals(c_network_port.LinkStatus, test_data.LinkStatus)
    lu.assertEquals(c_network_port.SpeedMbps, test_data.SpeedMbps)
    c_network_port.schedulers = origin_schedulers
    c_network_port.smbus_schedulers = origin_smbus_schedulers
    c_network_port.get_properties_res = origin_get_properties_res
end

function TEST_network_port:test_get_npu_port_basic_info()
    mock_network_port.npu_ipv4_obj = true
    mock_imu_info.ip_addr = INVALID_DATA_STRING
    mock_imu_info.subnet_mask = INVALID_DATA_STRING
    mock_imu_info.gateway = INVALID_DATA_STRING

    -- 测试npu仅能获取一个ipv4信息，当ip网关掩码均不变时不做资源树对象操作场景
    c_network_port.get_npu_port_basic_info(mock_network_port)
    lu.assertEquals(mock_network_port.npu_ipv4_info.Address, INVALID_DATA_STRING)

    -- 测试当ip网关掩码均为无效值时不上树场景
    mock_network_port.npu_ipv4_obj = false
    c_network_port.get_npu_port_basic_info(mock_network_port)
    lu.assertEquals(mock_network_port.npu_ipv4_info.Address, INVALID_DATA_STRING)

    -- 测试更新ipv4缓存信息并上树场景
    mock_imu_info.ip_addr = 'test_ip_addr_xx'
    mock_imu_info.subnet_mask = 'test_ip_addr'
    mock_imu_info.gateway = 'test_ip_addr'
    c_network_port.get_npu_port_basic_info(mock_network_port)
    lu.assertEquals(mock_network_port.npu_ipv4_obj.Address, 'test_ip_addr_xx')
    lu.assertEquals(mock_network_port.per_module_log_cnt, 0)
    lu.assertEquals(#mock_network_port.npu_port_log_buffer, 0)
end

function TEST_network_port:test_get_npu_port_hccs_info()
    c_network_port.get_npu_port_hccs_info(mock_network_port)
    lu.assertEquals(mock_network_port.hccs_info.first_error_lane, 255)
end

function TEST_network_port:test_update_npu_port_hccs_info()
    c_network_port.update_npu_port_hccs_info(mock_network_port, mock_imu_hccs_info)
    lu.assertEquals(mock_network_port.hccs_info.first_error_lane, 2)
end

function TEST_network_port:test_clear_hccs_info()
    mock_network_port.hccs_info.health_status = 1
    pcall(function ()
            c_network_port.clear_hccs_info(mock_network_port)
        end
    )
    lu.assertEquals(mock_network_port.hccs_info.health_status, 0)
end

function TEST_network_port:test_clear_npu_port_basic_info()
    mock_network_port.npu_ipv4_obj = {
        IPv4Address = 'test'
    }
    pcall(function ()
            c_network_port.clear_npu_port_basic_info(mock_network_port)
        end
    )
    lu.assertEquals(mock_network_port.npu_ipv4_info.Address, INVALID_DATA_STRING)
end

function TEST_network_port:test_get_npu_port_info()
    c_network_port.get_npu_port_info(mock_network_port)
end

function TEST_network_port:test_get_info_from_imu()
    c_network_port.get_info_from_imu(mock_network_port)
end

function TEST_network_port:test_get_npu_cdr_temp_from_imu_retry()
    local origin_get_npu_cdr_temp_from_imu = npu_imu_cmd.get_npu_cdr_temp_from_imu
    npu_imu_cmd.get_npu_cdr_temp_from_imu = function()
        return false
    end
    local ok = c_network_port:get_npu_cdr_temp_from_imu_retry()
    lu.assertIsTrue(ok)

    npu_imu_cmd.get_npu_cdr_temp_from_imu = origin_get_npu_cdr_temp_from_imu
end

function TEST_network_port:test_get_npu_cdr_temp_from_imu_fail()
    c_network_port.is_npu_heartbeat_loss = true
    c_network_port.get_npu_cdr_temp_from_imu(mock_network_port)
end

function TEST_network_port:test_get_npu_cdr_temp_from_imu()
    c_network_port.is_npu_heartbeat_loss = false
    c_network_port.get_npu_cdr_temp_from_imu(mock_network_port)

    local origin_get_power_status = fructl.get_power_status
    local origin_get_npu_cdr_temp_from_imu_retry = c_network_port.get_npu_cdr_temp_from_imu_retry
    fructl.get_power_status = function()
        return 'OFF'
    end
    local temp = c_network_port:get_npu_cdr_temp_from_imu()
    lu.assertEquals(temp, 0)

    fructl.get_power_status = function()
        return 'ON'
    end
    c_network_port.PowerOn = 1
    c_network_port.is_npu_heartbeat_loss = true
    c_network_port:get_npu_cdr_temp_from_imu()
    lu.assertIsTrue(c_network_port.npu_port_cdr_info_abnormal)

    c_network_port.is_npu_heartbeat_loss = false

    c_network_port.get_npu_cdr_temp_from_imu_retry = function()
        return true, true
    end
    c_network_port:get_npu_cdr_temp_from_imu()
    lu.assertIsFalse(c_network_port.npu_port_cdr_info_abnormal)

    c_network_port.get_npu_cdr_temp_from_imu_retry = function()
        return true, false
    end
    c_network_port:get_npu_cdr_temp_from_imu()
    lu.assertIsTrue(c_network_port.npu_port_cdr_info_abnormal)

    fructl.get_power_status = origin_get_power_status
    c_network_port.get_npu_cdr_temp_from_imu_retry = origin_get_npu_cdr_temp_from_imu_retry
end

function TEST_network_port:test_mctp()
    local original_new = context.new
    local original_get_context = context.get_context
    local original_set_context = context.set_context
    local original_get_parent = c_network_port.get_parent
    local data = {
        SpeedMbps = "SpeedMbps",
        AutoSpeedNegotiation = "AutoSpeedNegotiation",
        FullDuplex = "FullDuplex"
    }

    local mock_ctx = {
        initiator = 'test',
        is_empty = function() return false end,
        get_initiator = function() return 'test' end
    }
    context.new = function() return mock_ctx end
    context.get_context = function() return mock_ctx end
    context.set_context = function(ctx) end
    c_network_port.get_parent = function()
        return {
            Model = "CX4"
        }
    end
    c_network_port.schedulers = {}
    c_network_port.ncsi_config_obj = {
        GetLLDPCapability = function()
            return {
                on_data_change = { on = function(data) end },
                start = function () end
            }
        end,
        PortMetrics = function()
            return {
                on_data_change = { on = function(data) end },
                start = function () end
            }
        end,
        LinkStatus = function()
            return {
                on_data_change = { on = function(data) end },
                on_error = { on = function(data) end },
                start = function () end
            }
        end,
        InitializeNCSIChannel =  function() return { value = function() return {} end } end,
        BDF = function()
            return { value = function() return { bus = 1, device = 1, func = 1 } end }
        end,
        MacAddrNCSI =  function() return { value = function() return {} end } end,
        DefaultMacAddrNCSI =  function() return { value = function() return {} end } end,
        DCBX =  function()
            return {
                value = function()
                    return {}
                end,
                on_data_change = {
                    on = function(self, func)
                        func(data)
                    end
                },
                start = function () end
            }
        end,
        SetOnLLDPCapability =  function() return { value = function() return true end } end,
        SetOffLLDPCapability = function() return { value = function() return false end } end,
        ResetNic =  function() return { value = function() return {} end } end
    }
    c_network_port:update_LLDP_enabled_by_ncsi()
    c_network_port:update_ncsi_port_stats()
    c_network_port:update_ncsi_link_status()
    c_network_port:initialize_ncsi_channel()
    c_network_port:update_BDF_by_ncsi()
    c_network_port:update_DCBX_by_ncsi()
    c_network_port:set_package_id(1)

    c_network_port:set_LLDP_capability(true)
    pcall(function()
        c_network_port:set_LLDP_capability(false)
    end)

    context.new = original_new
    context.get_context = original_get_context
    context.set_context = original_set_context
    c_network_port.get_parent = original_get_parent
end

function TEST_network_port:test_mctp_mac()
    local original_new = context.new
    local original_get_context = context.get_context
    local original_set_context = context.set_context
    local pre_fun = c_network_port.get_parent
    local origin_get_properties_res = c_network_port.get_properties_res
    local origin_schedulers = c_network_port.smbus_schedulers
    local original_ncsi_config_obj = c_network_port.ncsi_config_obj
    c_network_port.get_parent = function()
        return {
            Model = "BroadCom"
        }
    end
    c_network_port.get_properties_res = {}
    c_network_port.smbus_schedulers = {}
    c_network_port.ncsi_config_obj = {
        MacAddrNCSI =  function()
            return {
                value = function()
                    return {}
                end,
                on_data_change = {
                    on = function(self, func)
                        func("asdf:asdf:asdf:asdf:asdf")
                    end
                },
                on_error = {
                    on = function(self, func)
                        func()
                    end
                },
                start = function () end
            }
        end,
        DefaultMacAddrNCSI =  function()
            return {
                value = function()
                    return {}
                end,
                on_data_change = {
                    on = function(self, func)
                        func("")
                    end
                },
                on_error = {
                    on = function(self, func)
                        func()
                    end
                },
                start = function () end
            }
        end
    }
    c_network_port:update_MAC_by_ncsi()
    c_network_port:update_default_MAC_by_ncsi()

    context.new = original_new
    context.get_context = original_get_context
    context.set_context = original_set_context
    c_network_port.get_parent = pre_fun
    c_network_port.get_properties_res = origin_get_properties_res
    c_network_port.smbus_schedulers = origin_schedulers
    c_network_port.ncsi_config_obj = original_ncsi_config_obj
end

local mockup_func = {}
local function mockup_func_backup()
    mockup_func.connect_signal = c_network_port.connect_signal
    mockup_func.get_power_status = fructl.get_power_status
    mockup_func.get_system_reset_flag = fructl.get_system_reset_flag
end
local function mockup_function()
    c_network_port.connect_signal = function(self, on_cb, cb)
        cb(self.name, self.value)
    end
    fructl.get_power_status = function()
        return "ON"
    end
end
local function mockup_func_restore()
    c_network_port.connect_signal = mockup_func.connect_signal
    fructl.get_power_status = mockup_func.get_power_status
    fructl.get_system_reset_flag = mockup_func.get_system_reset_flag
end

function TEST_network_port:test_start_npu_link_status_listening()
    mockup_func_backup()
    mockup_function()
    fructl.get_system_reset_flag = function()
        return 2
    end
    c_network_port.value = 0
    c_network_port.name = "LinkStatusValue"
    c_network_port.LinkStatusNumeric = 255
    c_network_port:start_npu_link_status_listening()
    lu.assertEquals(c_network_port.LinkStatusNumeric, 2)

    c_network_port.LinkStatusNumeric = 1
    c_network_port:start_npu_link_status_listening()
    lu.assertEquals(c_network_port.LinkStatusNumeric, 0)

    c_network_port.value = 1
    c_network_port:start_npu_link_status_listening()
    lu.assertEquals(c_network_port.LinkStatusNumeric, 1)

    mockup_func_restore()
end

function TEST_network_port:test_register_npu_changed_callback()
    mockup_func_backup()
    mockup_function()
    local start_npu_link_status_listening = c_network_port.start_npu_link_status_listening
    c_network_port.start_npu_link_status_listening = function()
    end
    fructl.get_system_reset_flag = function()
        return 0
    end
    c_network_port.LinkStatusValue = 1
    c_network_port:register_npu_changed_callback()
    lu.assertEquals(c_network_port.LinkStatusNumeric, 1)

    c_network_port.LinkStatusValue = 2
    c_network_port:register_npu_changed_callback()
    lu.assertEquals(c_network_port.LinkStatusNumeric, 2)

    c_network_port.start_npu_link_status_listening = start_npu_link_status_listening
    mockup_func_restore()
end

function TEST_network_port:test_npu_port_link_event()
    local origin = c_network_port.npu_port_get_diff_timestamp
    c_network_port.link_down_cnt = 1
    c_network_port.link_down_timestamp = {0}
    c_network_port.npu_port_log_buffer = {}
    c_network_port.per_module_log_cnt = 0
    c_network_port.NpuID = 1
    c_network_port:npu_port_link_event(mock_imu_info, true)
    lu.assertEquals(c_network_port.per_module_log_cnt, 1)
    c_network_port.npu_port_get_diff_timestamp = origin
end

-- 通用的mock设置函数
local function setup_redfish_lldp_mocks()
    local mocks = {}
    
    -- 保存原始值
    mocks.original_get_context = context.get_context
    mocks.original_get_parent = c_network_port.get_parent
    mocks.original_get_port_id = c_network_port.get_port_id
    mocks.original_ncsi_config_obj = c_network_port.ncsi_config_obj
    mocks.original_NodeId = c_network_port.NodeId
    mocks.original_NetworkAdapterId = c_network_port.NetworkAdapterId
    mocks.original_PortID = c_network_port.PortID
    mocks.original_package_id = c_network_port.package_id
    mocks.original_get_position = c_network_port.get_position
    
    -- Mock对象
    mocks.mock_ctx = {
        is_empty = function() return false end,
        get_initiator = function() return 'test_user' end
    }
    
    mocks.mock_parent_supported = {
        SupportedLLDP = true
    }
    
    mocks.mock_parent_not_supported = {
        SupportedLLDP = false
    }

    local dpu_obj = {}
    local extra_params = {}
    extra_params.Position = '00010102'
    dpu_obj.extra_params = extra_params
    mocks.set_mcu_on_result = true
    mocks.set_mcu_off_result = true
    dpu_obj.GetLLDPStatus = function()
        mocks.get_mcu_called = true
        return true
    end
    dpu_obj.SetLLDPStatus = function()
        mocks.set_mcu_called = true
        return true
    end
    client.GetDPUCardObjects = function()
        return {dpu_obj}
    end
    mocks.dpu = dpu_obj

    -- 控制变量
    mocks.set_on_called = false
    mocks.set_off_called = false
    mocks.reset_nic_called = false
    mocks.set_on_result = true
    mocks.set_off_result = true
    mocks.reset_nic_result = true
    
    return mocks
end

-- 应用通用的mock设置
local function apply_redfish_lldp_mocks(mocks)
    context.get_context = function() return mocks.mock_ctx end
    c_network_port.get_parent = function() return mocks.mock_parent_supported end
    c_network_port.get_port_id = function() return 1 end
    c_network_port.NodeId = 'test_node_1'
    c_network_port.NetworkAdapterId = 'NetworkAdapter_1'
    c_network_port.PortID = 1
    c_network_port.package_id = 0
    c_network_port.get_position = function() return '00010102' end
    
    c_network_port.ncsi_config_obj = {
        SetOnLLDPCapability = function()
            mocks.set_on_called = true
            return { value = function() return mocks.set_on_result end }
        end,
        SetOffLLDPCapability = function()
            mocks.set_off_called = true
            return { value = function() return mocks.set_off_result end }
        end,
        ResetNic = function()
            mocks.reset_nic_called = true
            return { value = function() return mocks.reset_nic_result end }
        end
    }
end

-- 还原所有mock
local function restore_redfish_lldp_mocks(mocks)
    context.get_context = mocks.original_get_context
    c_network_port.get_parent = mocks.original_get_parent
    c_network_port.get_port_id = mocks.original_get_port_id
    c_network_port.ncsi_config_obj = mocks.original_ncsi_config_obj
    c_network_port.NodeId = mocks.original_NodeId
    c_network_port.NetworkAdapterId = mocks.original_NetworkAdapterId
    c_network_port.PortID = mocks.original_PortID
    c_network_port.package_id = mocks.original_package_id
end

-- 测试成功场景
function TEST_network_port:test_redfish_set_lldp_capability_success()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)
    
    -- 测试启用LLDP (非CX4网卡)
    mocks.set_on_called = false
    mocks.reset_nic_called = false
    
    c_network_port:redfish_set_lldp_capability(true)
    
    lu.assertIsTrue(mocks.set_on_called, "SetOnLLDPCapability should be called")
    lu.assertIsFalse(mocks.reset_nic_called, "ResetNic should NOT be called for non-CX4")
    
    -- 测试禁用LLDP (非CX4网卡)
    mocks.set_off_called = false
    mocks.reset_nic_called = false
    
    c_network_port:redfish_set_lldp_capability(false)
    
    lu.assertIsTrue(mocks.set_off_called, "SetOffLLDPCapability should be called")
    lu.assertIsFalse(mocks.reset_nic_called, "ResetNic should NOT be called for non-CX4")
    
    restore_redfish_lldp_mocks(mocks)
end

-- 测试调用mcu通路成功场景
function TEST_network_port:test_redfish_set_lldp_capability_by_mcu()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)

    -- 测试启用LLDP (非CX4网卡)
    mocks.set_mcu_called = false
    c_network_port.WorkloadType = 1

    c_network_port:redfish_set_lldp_capability(true)

    lu.assertIsTrue(mocks.set_mcu_called, "set lldp on by mcu failed")

    -- 测试禁用LLDP (非CX4网卡)
    c_network_port:redfish_set_lldp_capability(false)

    lu.assertIsTrue(mocks.set_mcu_called, "set lldp off by mcu failed")

    restore_redfish_lldp_mocks(mocks)
end

-- 测试调用mcu通路成功场景
function TEST_network_port:test_redfish_set_lldp_capability_by_mcu_failed()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)

    mocks.dpu.extra_params.Position = '00010103'
    local success, _ = pcall(function()
        c_network_port:redfish_set_lldp_capability(true)
    end)
    lu.assertIsFalse(success, "can not get dpu object")

    mocks.dpu.extra_params.Position = '00010102'
    mocks.dpu.SetLLDPStatus = function()
        return error('error')
    end
    local success, _ = pcall(function()
        c_network_port:redfish_set_lldp_capability(true)
    end)
    lu.assertIsFalse(success, "set lldp failed")

    restore_redfish_lldp_mocks(mocks)
end

-- 测试调用mcu通路更新LLDP失败场景
function TEST_network_port:test_update_LLDP_enabled_by_mcu_failed()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)

    mocks.dpu.extra_params.Position = '00010103'
    c_network_port:update_LLDP_enabled_by_mcu()
    lu.assertIsFalse(false, "can not get dpu object")

    mocks.dpu.extra_params.Position = '00010102'
    mocks.dpu.GetLLDPStatus = function()
        return error('error')
    end
    c_network_port:update_LLDP_enabled_by_mcu()
    lu.assertIsFalse(false, "get lldp failed")

    restore_redfish_lldp_mocks(mocks)
end

-- 测试调用mcu更新LLDP成功场景
function TEST_network_port:test_update_LLDP_enabled_by_mcu()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)

    -- 测试更新LLDP (非CX4网卡)
    mocks.get_mcu_called = false

    c_network_port:update_LLDP_enabled_by_mcu()

    lu.assertIsTrue(mocks.get_mcu_called, "get lldp by mcu failed")

    restore_redfish_lldp_mocks(mocks)
end

-- 测试CX4网卡的特殊处理
function TEST_network_port:test_redfish_set_lldp_capability_cx4()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)
    
    -- 设置CX4网卡
    local mock_parent_cx4 = {
        SupportedLLDP = true,
        Model = 'CX4'
    }
    c_network_port.get_parent = function() return mock_parent_cx4 end
    c_network_port.WorkloadType = function() return 0 end
    
    -- 测试CX4启用LLDP成功
    mocks.set_on_called = false
    mocks.reset_nic_called = false
    
    c_network_port:redfish_set_lldp_capability(true)
    
    lu.assertIsTrue(mocks.set_on_called, "SetOnLLDPCapability should be called for CX4")
    lu.assertIsTrue(mocks.reset_nic_called, "ResetNic should be called for CX4")
    
    -- 测试CX4禁用LLDP成功
    mocks.set_off_called = false
    mocks.reset_nic_called = false
    
    c_network_port:redfish_set_lldp_capability(false)
    
    lu.assertIsTrue(mocks.set_off_called, "SetOffLLDPCapability should be called for CX4")
    lu.assertIsTrue(mocks.reset_nic_called, "ResetNic should be called for CX4")
    
    restore_redfish_lldp_mocks(mocks)
end

-- 测试CX4网卡ResetNic失败的场景
function TEST_network_port:test_redfish_set_lldp_capability_cx4_reset_fail()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)
    
    -- 设置CX4网卡
    local mock_parent_cx4 = {
        SupportedLLDP = true,
        Model = 'CX4'
    }
    c_network_port.get_parent = function() return mock_parent_cx4 end
    
    -- 设置ResetNic失败
    mocks.reset_nic_result = false
    
    local success, _ = pcall(function()
        c_network_port:redfish_set_lldp_capability(true)
    end)
    
    lu.assertIsFalse(success, "Should fail when CX4 ResetNic fails")
    lu.assertIsTrue(mocks.set_on_called, "SetOnLLDPCapability should be called before ResetNic fails")
    lu.assertIsTrue(mocks.reset_nic_called, "ResetNic should be called for CX4")
    
    restore_redfish_lldp_mocks(mocks)
end

-- 测试非CX4网卡的正常处理
function TEST_network_port:test_redfish_set_lldp_capability_non_cx4()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)
    
    -- 测试不同型号的非CX4网卡
    local test_models = {'Intel', 'Broadcom', 'Mellanox', 'Other'}
    
    for _, model in ipairs(test_models) do
        local mock_parent_non_cx4 = {
            SupportedLLDP = true,
            Model = model
        }
        c_network_port.get_parent = function() return mock_parent_non_cx4 end
        
        -- 重置状态
        mocks.set_on_called = false
        mocks.reset_nic_called = false
        
        c_network_port:redfish_set_lldp_capability(true)
        
        lu.assertIsTrue(mocks.set_on_called, 
            string.format("SetOnLLDPCapability should be called for %s", model))
        lu.assertIsFalse(mocks.reset_nic_called, 
            string.format("ResetNic should NOT be called for %s", model))
    end
    
    restore_redfish_lldp_mocks(mocks)
end

-- 测试不支持LLDP的场景
function TEST_network_port:test_redfish_set_lldp_capability_not_supported()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)
    
    -- 设置不支持LLDP的父对象
    c_network_port.get_parent = function() return mocks.mock_parent_not_supported end
    
    local success, _ = pcall(function()
        c_network_port:redfish_set_lldp_capability(true)
    end)
    
    lu.assertIsFalse(success, "Should fail when LLDP not supported")
    
    restore_redfish_lldp_mocks(mocks)
end

-- 测试NCSI命令失败场景
function TEST_network_port:test_redfish_set_lldp_capability_failures()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)
    
    -- 测试SetOnLLDPCapability失败
    mocks.set_on_result = false
    local success, _ = pcall(function()
        c_network_port:redfish_set_lldp_capability(true)
    end)
    lu.assertIsFalse(success, "Should fail when SetOnLLDPCapability fails")
    
    -- 测试SetOffLLDPCapability失败
    mocks.set_on_result = true
    mocks.set_off_result = false
    success, _ = pcall(function()
        c_network_port:redfish_set_lldp_capability(false)
    end)
    lu.assertIsFalse(success, "Should fail when SetOffLLDPCapability fails")
    
    restore_redfish_lldp_mocks(mocks)
end

-- 测试Context相关场景
function TEST_network_port:test_redfish_set_lldp_capability_context()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)
    
    -- 测试无context的情况
    context.get_context = function() return nil end
    c_network_port:redfish_set_lldp_capability(true)
    
    -- 测试空context的情况
    local mock_empty_ctx = {
        is_empty = function() return true end
    }
    context.get_context = function() return mock_empty_ctx end
    c_network_port:redfish_set_lldp_capability(false)
    
    restore_redfish_lldp_mocks(mocks)
end

-- 测试异常处理场景
function TEST_network_port:test_redfish_set_lldp_capability_exceptions()
    local mocks = setup_redfish_lldp_mocks()
    apply_redfish_lldp_mocks(mocks)
    
    -- 测试SetOnLLDPCapability抛出异常
    c_network_port.ncsi_config_obj.SetOnLLDPCapability = function()
        error("Mock exception")
    end
    local success, _ = pcall(function()
        c_network_port:redfish_set_lldp_capability(true)
    end)
    lu.assertIsFalse(success, "Should fail when SetOnLLDPCapability throws exception")
    
    -- 测试SetOffLLDPCapability抛出异常
    c_network_port.ncsi_config_obj.SetOffLLDPCapability = function()
        error("Mock exception")
    end
    success, _ = pcall(function()
        c_network_port:redfish_set_lldp_capability(false)
    end)
    lu.assertIsFalse(success, "Should fail when SetOffLLDPCapability throws exception")
    
    -- 测试CX4网卡ResetNic抛出异常
    local mock_parent_cx4 = {
        SupportedLLDP = true,
        Model = 'CX4'
    }
    c_network_port.get_parent = function() return mock_parent_cx4 end
    c_network_port.ncsi_config_obj.SetOnLLDPCapability = function()
        mocks.set_on_called = true
        return { value = function() return mocks.set_on_result end }
    end
    c_network_port.ncsi_config_obj.ResetNic = function()
        error("Mock exception")
    end
    success, _ = pcall(function()
        c_network_port:redfish_set_lldp_capability(true)
    end)
    lu.assertIsFalse(success, "Should fail when CX4 ResetNic throws exception")
    
    restore_redfish_lldp_mocks(mocks)
end

-- 测试日志操作封装函数
function TEST_network_port:test_log_lldp_operation()
    local original_get_context = context.get_context
    local original_NodeId = c_network_port.NodeId
    local original_NetworkAdapterId = c_network_port.NetworkAdapterId  
    local original_PortID = c_network_port.PortID
    
    -- 设置测试数据
    c_network_port.NodeId = 'test_node_1'
    c_network_port.NetworkAdapterId = 'NetworkAdapter_1'
    c_network_port.PortID = 1
    
    local mock_ctx = {
        is_empty = function() return false end,
        get_initiator = function() return 'test_user' end
    }
    
    -- 测试有context且成功的情况
    context.get_context = function() return mock_ctx end
    c_network_port:log_lldp_operation(true, mock_ctx, true)
    
    -- 测试有context但失败的情况  
    c_network_port:log_lldp_operation(false, mock_ctx, false)
    
    -- 测试空context的情况
    local mock_empty_ctx = {
        is_empty = function() return true end
    }
    c_network_port:log_lldp_operation(true, mock_empty_ctx, true)
    
    -- 测试nil context的情况
    c_network_port:log_lldp_operation(false, nil, false)
    
    -- 还原原始值
    context.get_context = original_get_context
    c_network_port.NodeId = original_NodeId
    c_network_port.NetworkAdapterId = original_NetworkAdapterId
    c_network_port.PortID = original_PortID
end

function TEST_network_port:test_npu_drive_monitor()
    local c_PortID = c_network_port.PortID
    local c_LinkStatusValue = c_network_port.LinkStatusValue
    local c_PowerOn = c_network_port.PowerOn
    local c_LinkDown = c_network_port.LinkDown
    local c_MediumType = c_network_port.MediumType
    c_network_port.PortID = 1
    c_network_port.LinkStatusValue = 0
    c_network_port.PowerOn = 0
    c_network_port.LinkDown = 0
    c_network_port.MediumType = "FiberOptic"
    local time = 0
    local c_sleep_ms = c_network_port.sleep_ms
    c_network_port.sleep_ms = function()
        time = time + 60000
        if time > 1000000 then
            time = 0
            error()
        elseif time > 60000 then
            c_network_port.PowerOn = 1
        end
    end
    local c_vos_tick_get = vos.vos_tick_get
    vos.vos_tick_get = function()
        return time
    end
    local c_collection = c_optical_module.collection
    local tab = {
        {
            RelatedNetworkPorts = {0,1},
            RXInputPowerMilliWatts = {1}
        }
    }
    c_optical_module.collection = {
        fold = function(obj, cb)
            for _, v in pairs(tab) do
                cb(_, v)
            end
        end
    }
    pcall(function()
        c_network_port:npu_driver_monitor()
    end)
    lu.assertEquals(c_network_port.LinkDown, 1)
    c_network_port.sleep_ms = c_sleep_ms
    vos.vos_tick_get = c_vos_tick_get
    c_optical_module.collection = c_collection
    c_network_port.PortID = c_PortID
    c_network_port.LinkStatusValue = c_LinkStatusValue
    c_network_port.PowerOn = c_PowerOn
    c_network_port.LinkDown = c_LinkDown
    c_network_port.MediumType = c_MediumType
end

-- 测试update_ncsi_link_status函数的NCSI恢复时停止SMBUS fallback逻辑
function TEST_network_port:test_update_ncsi_link_status_ncsi_recovered_stops_smbus_fallback()
    -- 备份原始状态
    local original_schedulers = c_network_port.schedulers
    local original_smbus_schedulers = c_network_port.smbus_schedulers
    local original_ncsi_config_obj = c_network_port.ncsi_config_obj
    local original_package_id = c_network_port.package_id
    local original_get_port_id = c_network_port.get_port_id
    local original_t_port_prop_without_bma = c_network_port.t_port_prop_without_bma
    local original_ncsi_get_linkstatus_retry_count = c_network_port.ncsi_get_linkstatus_retry_count
    local original_get_ncsi_link_status_succeess = c_network_port.get_ncsi_link_status_succeess
    local original_LinkStatus = c_network_port.LinkStatus
    local original_SpeedMbps = c_network_port.SpeedMbps
    local original_AutoSpeedNegotiation = c_network_port.AutoSpeedNegotiation
    local original_FullDuplex = c_network_port.FullDuplex
    
    -- 初始化测试状态
    c_network_port.schedulers = {}
    c_network_port.smbus_schedulers = {}
    c_network_port.package_id = 0
    c_network_port.get_port_id = function() return 1 end
    c_network_port.t_port_prop_without_bma = {}
    c_network_port.ncsi_get_linkstatus_retry_count = 0
    c_network_port.get_ncsi_link_status_succeess = false
    
    -- 模拟SMBUS任务正在运行
    local smbus_task_paused = false
    c_network_port.smbus_schedulers.link_status_task = {
        is_paused = false,
        pause = function() smbus_task_paused = true end,
        data = "some_data"
    }
    
    -- 模拟NCSI配置对象
    local scheduler_mock = {
        on_data_change = {
            on = function(self, callback)
                self.callback = callback
            end
        },
        on_error = {
            on = function(self, callback)
                self.error_callback = callback
            end
        },
        start = function() end
    }
    
    c_network_port.ncsi_config_obj = {
        LinkStatus = function(params) return scheduler_mock end
    }
    
    -- 打桩外部依赖
    local original_table_insert = table.insert
    table.insert = function() end
    
    -- 执行函数
    c_network_port:update_ncsi_link_status()
    
    -- 模拟NCSI数据变化（恢复正常）
    local link_data = {
        LinkStatus = 'LinkUp',
        SpeedMbps = 1000,
        AutoSpeedNegotiation = true,
        FullDuplex = true
    }
    scheduler_mock.on_data_change.callback(link_data)
    
    -- 验证结果
    lu.assertEquals(c_network_port.LinkStatus, link_data.LinkStatus)
    lu.assertEquals(c_network_port.SpeedMbps, link_data.SpeedMbps)
    lu.assertEquals(c_network_port.AutoSpeedNegotiation, link_data.AutoSpeedNegotiation)
    lu.assertEquals(c_network_port.FullDuplex, link_data.FullDuplex)
    lu.assertTrue(smbus_task_paused)
    lu.assertNil(c_network_port.smbus_schedulers.link_status_task.data)
    
    -- 还原打桩
    table.insert = original_table_insert
    
    -- 还原全局状态
    c_network_port.schedulers = original_schedulers
    c_network_port.smbus_schedulers = original_smbus_schedulers
    c_network_port.ncsi_config_obj = original_ncsi_config_obj
    c_network_port.package_id = original_package_id
    c_network_port.get_port_id = original_get_port_id
    c_network_port.t_port_prop_without_bma = original_t_port_prop_without_bma
    c_network_port.ncsi_get_linkstatus_retry_count = original_ncsi_get_linkstatus_retry_count
    c_network_port.get_ncsi_link_status_succeess = original_get_ncsi_link_status_succeess
    c_network_port.LinkStatus = original_LinkStatus
    c_network_port.SpeedMbps = original_SpeedMbps
    c_network_port.AutoSpeedNegotiation = original_AutoSpeedNegotiation
    c_network_port.FullDuplex = original_FullDuplex
end

-- 测试update_ncsi_link_status函数的NCSI失败时启动SMBUS fallback逻辑
function TEST_network_port:test_update_ncsi_link_status_ncsi_failed_activates_smbus_fallback()
    -- 备份原始状态
    local original_schedulers = c_network_port.schedulers
    local original_smbus_schedulers = c_network_port.smbus_schedulers
    local original_ncsi_config_obj = c_network_port.ncsi_config_obj
    local original_package_id = c_network_port.package_id
    local original_get_port_id = c_network_port.get_port_id
    local original_t_port_prop_without_bma = c_network_port.t_port_prop_without_bma
    local original_ncsi_get_linkstatus_retry_count = c_network_port.ncsi_get_linkstatus_retry_count
    local original_get_ncsi_link_status_succeess = c_network_port.get_ncsi_link_status_succeess
    local original_LinkStatus = c_network_port.LinkStatus
    local original_SpeedMbps = c_network_port.SpeedMbps
    local original_AutoSpeedNegotiation = c_network_port.AutoSpeedNegotiation
    local original_FullDuplex = c_network_port.FullDuplex
    
    -- 初始化测试状态
    c_network_port.schedulers = {}
    c_network_port.smbus_schedulers = {}
    c_network_port.package_id = 0
    c_network_port.get_port_id = function() return 1 end
    c_network_port.t_port_prop_without_bma = {}
    c_network_port.ncsi_get_linkstatus_retry_count = 0
    c_network_port.get_ncsi_link_status_succeess = false
    
    -- 模拟SMBUS任务已暂停
    local smbus_task_resumed = false
    c_network_port.smbus_schedulers.link_status_task = {
        is_paused = true,
        resume = function() smbus_task_resumed = true end
    }
    
    -- 模拟NCSI配置对象
    local scheduler_mock = {
        on_data_change = {
            on = function(self, callback)
                self.callback = callback
            end
        },
        on_error = {
            on = function(self, callback)
                self.error_callback = callback
            end
        },
        start = function() end
    }
    
    c_network_port.ncsi_config_obj = {
        LinkStatus = function(params) return scheduler_mock end
    }
    
    -- 打桩外部依赖
    local original_table_insert = table.insert
    table.insert = function() end
    
    -- 执行函数
    c_network_port:update_ncsi_link_status()
    
    -- 模拟NCSI连续失败达到阈值（NCSI_FAILED_THRESHOLD = 3）
    for i = 1, 3 do
        scheduler_mock.on_error.error_callback()
    end
    
    -- 验证结果
    lu.assertTrue(smbus_task_resumed)
    
    -- 还原打桩
    table.insert = original_table_insert
    
    -- 还原全局状态
    c_network_port.schedulers = original_schedulers
    c_network_port.smbus_schedulers = original_smbus_schedulers
    c_network_port.ncsi_config_obj = original_ncsi_config_obj
    c_network_port.package_id = original_package_id
    c_network_port.get_port_id = original_get_port_id
    c_network_port.t_port_prop_without_bma = original_t_port_prop_without_bma
    c_network_port.ncsi_get_linkstatus_retry_count = original_ncsi_get_linkstatus_retry_count
    c_network_port.get_ncsi_link_status_succeess = original_get_ncsi_link_status_succeess
    c_network_port.LinkStatus = original_LinkStatus
    c_network_port.SpeedMbps = original_SpeedMbps
    c_network_port.AutoSpeedNegotiation = original_AutoSpeedNegotiation
    c_network_port.FullDuplex = original_FullDuplex
end

-- 测试update_MAC_by_ncsi函数的NCSI恢复时停止SMBUS fallback逻辑
function TEST_network_port:test_update_MAC_by_ncsi_ncsi_recovered_stops_smbus_fallback()
    -- 备份原始状态
    local original_schedulers = c_network_port.schedulers
    local original_smbus_schedulers = c_network_port.smbus_schedulers
    local original_ncsi_config_obj = c_network_port.ncsi_config_obj
    local original_package_id = c_network_port.package_id
    local original_get_port_id = c_network_port.get_port_id
    local original_get_parent = c_network_port.get_parent
    local original_get_properties_res = c_network_port.get_properties_res
    local original_MACAddress = c_network_port.MACAddress
    
    -- 初始化测试状态
    c_network_port.schedulers = {}
    c_network_port.smbus_schedulers = {}
    c_network_port.package_id = 0
    c_network_port.get_port_id = function() return 1 end
    c_network_port.get_properties_res = {}
    
    -- 模拟父对象
    c_network_port.get_parent = function()
        return { Model = 'BroadCom' }
    end
    
    -- 模拟SMBUS任务正在运行
    local smbus_task_paused = false
    c_network_port.smbus_schedulers.mac_address_task = {
        is_paused = false,
        pause = function() smbus_task_paused = true end,
        data = "some_data"
    }
    
    -- 模拟NCSI配置对象
    local scheduler_mock = {
        on_data_change = {
            on = function(self, callback)
                self.callback = callback
            end
        },
        on_error = {
            on = function(self, callback)
                self.error_callback = callback
            end
        },
        start = function() end
    }
    
    c_network_port.ncsi_config_obj = {
        MacAddrNCSI = function(params) return scheduler_mock end
    }
    
    -- 打桩外部依赖
    local original_table_insert = table.insert
    table.insert = function() end
    
    -- 执行函数
    c_network_port:update_MAC_by_ncsi()
    
    -- 模拟NCSI数据变化（恢复正常）
    local mac_data = 'AA:BB:CC:DD:EE:FF'
    scheduler_mock.on_data_change.callback(mac_data)
    
    -- 验证结果
    lu.assertEquals(c_network_port.MACAddress, mac_data)
    lu.assertTrue(c_network_port.get_properties_res.MacAddressFromNcsi)
    lu.assertTrue(smbus_task_paused)
    lu.assertNil(c_network_port.smbus_schedulers.mac_address_task.data)
    
    -- 还原打桩
    table.insert = original_table_insert
    
    -- 还原全局状态
    c_network_port.schedulers = original_schedulers
    c_network_port.smbus_schedulers = original_smbus_schedulers
    c_network_port.ncsi_config_obj = original_ncsi_config_obj
    c_network_port.package_id = original_package_id
    c_network_port.get_port_id = original_get_port_id
    c_network_port.get_parent = original_get_parent
    c_network_port.get_properties_res = original_get_properties_res
    c_network_port.MACAddress = original_MACAddress
end

-- 测试update_MAC_by_ncsi函数的NCSI失败时启动SMBUS fallback逻辑
function TEST_network_port:test_update_MAC_by_ncsi_ncsi_failed_activates_smbus_fallback()
    -- 备份原始状态
    local original_schedulers = c_network_port.schedulers
    local original_smbus_schedulers = c_network_port.smbus_schedulers
    local original_ncsi_config_obj = c_network_port.ncsi_config_obj
    local original_package_id = c_network_port.package_id
    local original_get_port_id = c_network_port.get_port_id
    local original_get_parent = c_network_port.get_parent
    local original_get_properties_res = c_network_port.get_properties_res
    local original_MACAddress = c_network_port.MACAddress
    
    -- 初始化测试状态
    c_network_port.schedulers = {}
    c_network_port.smbus_schedulers = {}
    c_network_port.package_id = 0
    c_network_port.get_port_id = function() return 1 end
    c_network_port.get_properties_res = {MacAddressFromNcsi = true}
    
    -- 模拟父对象
    c_network_port.get_parent = function()
        return { Model = 'BroadCom' }
    end
    
    -- 模拟SMBUS任务已暂停
    local smbus_task_resumed = false
    c_network_port.smbus_schedulers.mac_address_task = {
        is_paused = true,
        resume = function() smbus_task_resumed = true end
    }
    
    -- 模拟NCSI配置对象
    local scheduler_mock = {
        on_data_change = {
            on = function(self, callback)
                self.callback = callback
            end
        },
        on_error = {
            on = function(self, callback)
                self.error_callback = callback
            end
        },
        start = function() end
    }
    
    c_network_port.ncsi_config_obj = {
        MacAddrNCSI = function(params) return scheduler_mock end
    }
    
    -- 打桩外部依赖
    local original_table_insert = table.insert
    table.insert = function() end
    
    -- 执行函数
    c_network_port:update_MAC_by_ncsi()
    
    -- 模拟NCSI连续失败达到阈值（NCSI_FAILED_THRESHOLD = 3）
    for i = 1, 3 do
        scheduler_mock.on_error.error_callback()
    end
    
    -- 验证结果
    lu.assertFalse(c_network_port.get_properties_res.MacAddressFromNcsi)
    lu.assertTrue(smbus_task_resumed)
    
    -- 还原打桩
    table.insert = original_table_insert
    
    -- 还原全局状态
    c_network_port.schedulers = original_schedulers
    c_network_port.smbus_schedulers = original_smbus_schedulers
    c_network_port.ncsi_config_obj = original_ncsi_config_obj
    c_network_port.package_id = original_package_id
    c_network_port.get_port_id = original_get_port_id
    c_network_port.get_parent = original_get_parent
    c_network_port.get_properties_res = original_get_properties_res
    c_network_port.MACAddress = original_MACAddress
end

-- 测试update_BDF_by_ncsi函数的while循环逻辑
function TEST_network_port:test_update_BDF_by_ncsi_while_loop_logic()
    -- 备份原始状态
    local original_ncsi_config_obj = c_network_port.ncsi_config_obj
    local original_package_id = c_network_port.package_id
    local original_get_port_id = c_network_port.get_port_id
    local original_bdf_task_is_running = c_network_port.bdf_task_is_running
    local original_next_tick = c_network_port.next_tick
    local original_sleep_ms = c_network_port.sleep_ms
    local original_WorkloadType = c_network_port.WorkloadType
    local original_BDF = c_network_port.BDF
    
    -- 初始化测试状态
    c_network_port.package_id = 0
    c_network_port.get_port_id = function() return 1 end
    c_network_port.bdf_task_is_running = false
    c_network_port.WorkloadType = 0
    
    -- 模拟BDF获取成功的情况
    local call_count = 0
    c_network_port.ncsi_config_obj = {
        BDF = function(params)
            call_count = call_count + 1
            return {
                value = function()
                    if call_count == 1 then
                        return { bus = 0, device = 0, func = 0 } -- 无效BDF
                    else
                        return { bus = 1, device = 2, func = 3 } -- 有效BDF
                    end
                end
            }
        end
    }
    
    -- 模拟next_tick和sleep_ms
    local task_executed = false
    c_network_port.next_tick = function(self, func)
        task_executed = true
        func() -- 立即执行任务
    end
    
    c_network_port.sleep_ms = function()
    end
    
    -- 执行函数
    c_network_port:update_BDF_by_ncsi()
    
    -- 验证结果
    lu.assertTrue(task_executed)
    lu.assertEquals(call_count, 2) -- 应该调用两次：第一次无效，第二次有效
    lu.assertEquals(c_network_port.BDF, '0000:01:02.3')
    lu.assertFalse(c_network_port.bdf_task_is_running)
    
    -- 还原全局状态
    c_network_port.ncsi_config_obj = original_ncsi_config_obj
    c_network_port.package_id = original_package_id
    c_network_port.get_port_id = original_get_port_id
    c_network_port.bdf_task_is_running = original_bdf_task_is_running
    c_network_port.next_tick = original_next_tick
    c_network_port.sleep_ms = original_sleep_ms
    c_network_port.WorkloadType = original_WorkloadType
    c_network_port.BDF = original_BDF
end

-- 测试update_BDF_by_ncsi函数的重复调用保护
function TEST_network_port:test_update_BDF_by_ncsi_duplicate_call_protection()
    -- 备份原始状态
    local original_ncsi_config_obj = c_network_port.ncsi_config_obj
    local original_bdf_task_is_running = c_network_port.bdf_task_is_running
    local original_next_tick = c_network_port.next_tick
    
    -- 设置任务正在运行
    c_network_port.bdf_task_is_running = true
    c_network_port.ncsi_config_obj = {
        BDF = function(params)
            return { value = function() return { bus = 1, device = 2, func = 3 } end }
        end
    }
    
    -- 模拟next_tick
    local task_executed = false
    c_network_port.next_tick = function(self, func)
        task_executed = true
        func()
    end
    
    -- 执行函数
    c_network_port:update_BDF_by_ncsi()
    
    -- 验证结果：任务不应该被执行
    lu.assertFalse(task_executed)
    
    -- 还原全局状态
    c_network_port.ncsi_config_obj = original_ncsi_config_obj
    c_network_port.bdf_task_is_running = original_bdf_task_is_running
    c_network_port.next_tick = original_next_tick
end

-- 测试update_BDF_by_ncsi函数的BDF配置对象不存在的情况
function TEST_network_port:test_update_BDF_by_ncsi_no_bdf_config()
    -- 备份原始状态
    local original_ncsi_config_obj = c_network_port.ncsi_config_obj
    local original_bdf_task_is_running = c_network_port.bdf_task_is_running
    local original_next_tick = c_network_port.next_tick
    
    -- 设置BDF配置对象不存在
    c_network_port.ncsi_config_obj = {}
    c_network_port.bdf_task_is_running = false
    
    -- 模拟next_tick
    local task_executed = false
    c_network_port.next_tick = function(self, func)
        task_executed = true
        func()
    end
    
    -- 执行函数
    c_network_port:update_BDF_by_ncsi()
    
    -- 验证结果：任务不应该被执行
    lu.assertFalse(task_executed)
    
    -- 还原全局状态
    c_network_port.ncsi_config_obj = original_ncsi_config_obj
    c_network_port.bdf_task_is_running = original_bdf_task_is_running
    c_network_port.next_tick = original_next_tick
end

-- 测试当SMBUS任务已暂停时NCSI恢复不会重复暂停
function TEST_network_port:test_ncsi_recovered_when_smbus_already_paused()
    -- 备份原始状态
    local original_schedulers = c_network_port.schedulers
    local original_smbus_schedulers = c_network_port.smbus_schedulers
    local original_ncsi_config_obj = c_network_port.ncsi_config_obj
    local original_package_id = c_network_port.package_id
    local original_get_port_id = c_network_port.get_port_id
    local original_t_port_prop_without_bma = c_network_port.t_port_prop_without_bma
    local original_ncsi_get_linkstatus_retry_count = c_network_port.ncsi_get_linkstatus_retry_count
    local original_get_ncsi_link_status_succeess = c_network_port.get_ncsi_link_status_succeess
    local original_LinkStatus = c_network_port.LinkStatus
    local original_SpeedMbps = c_network_port.SpeedMbps
    local original_AutoSpeedNegotiation = c_network_port.AutoSpeedNegotiation
    local original_FullDuplex = c_network_port.FullDuplex
    
    -- 初始化测试状态
    c_network_port.schedulers = {}
    c_network_port.smbus_schedulers = {}
    c_network_port.package_id = 0
    c_network_port.get_port_id = function() return 1 end
    c_network_port.t_port_prop_without_bma = {}
    c_network_port.ncsi_get_linkstatus_retry_count = 0
    c_network_port.get_ncsi_link_status_succeess = false
    
    -- 模拟SMBUS任务已暂停
    local pause_call_count = 0
    c_network_port.smbus_schedulers.link_status_task = {
        is_paused = true,
        pause = function() pause_call_count = pause_call_count + 1 end,
        data = "some_data"
    }
    
    -- 模拟NCSI配置对象
    local scheduler_mock = {
        on_data_change = {
            on = function(self, callback)
                self.callback = callback
            end
        },
        on_error = {
            on = function(self, callback)
                self.error_callback = callback
            end
        },
        start = function() end
    }
    
    c_network_port.ncsi_config_obj = {
        LinkStatus = function(params) return scheduler_mock end
    }
    
    -- 打桩外部依赖
    local original_table_insert = table.insert
    table.insert = function() end
    
    -- 执行函数
    c_network_port:update_ncsi_link_status()
    
    -- 模拟NCSI数据变化（恢复正常）
    local link_data = {
        LinkStatus = 'LinkUp',
        SpeedMbps = 1000,
        AutoSpeedNegotiation = true,
        FullDuplex = true
    }
    scheduler_mock.on_data_change.callback(link_data)
    
    -- 验证结果：不应该重复调用pause，因为任务已经暂停
    lu.assertEquals(pause_call_count, 0)
    lu.assertEquals(c_network_port.LinkStatus, link_data.LinkStatus)
    
    -- 还原打桩
    table.insert = original_table_insert
    
    -- 还原全局状态
    c_network_port.schedulers = original_schedulers
    c_network_port.smbus_schedulers = original_smbus_schedulers
    c_network_port.ncsi_config_obj = original_ncsi_config_obj
    c_network_port.package_id = original_package_id
    c_network_port.get_port_id = original_get_port_id
    c_network_port.t_port_prop_without_bma = original_t_port_prop_without_bma
    c_network_port.ncsi_get_linkstatus_retry_count = original_ncsi_get_linkstatus_retry_count
    c_network_port.get_ncsi_link_status_succeess = original_get_ncsi_link_status_succeess
    c_network_port.LinkStatus = original_LinkStatus
    c_network_port.SpeedMbps = original_SpeedMbps
    c_network_port.AutoSpeedNegotiation = original_AutoSpeedNegotiation
    c_network_port.FullDuplex = original_FullDuplex
end