-- Copyright (c) 2026 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 ipmi = require 'ipmi'
local drive_collection = require 'drive.drive_collection'
local rpc_service_nvme_drive = require 'rpc_services.rpc_service_nvme_drive'

TestRpcServiceNvmeDrive = {}

function TestRpcServiceNvmeDrive:setUp()
    self.ds = drive_collection.get_instance()
    self._orig_nvme_list = self.ds.nvme_list
end

function TestRpcServiceNvmeDrive:tearDown()
    if self.ds then
        self.ds.nvme_list = self._orig_nvme_list
    end
end

function TestRpcServiceNvmeDrive:test_get_nvme_drive_count_without_list()
    self.ds.nvme_list = nil
    local cc = rpc_service_nvme_drive:get_nvme_drive_count()
    lu.assertEquals(cc, ipmi.types.Cc.UnspecifiedError)
end

function TestRpcServiceNvmeDrive:test_get_nvme_drive_count_with_list()
    self.ds.nvme_list = { {}, {} }
    local count = rpc_service_nvme_drive:get_nvme_drive_count()
    lu.assertEquals(count, 2)
end

function TestRpcServiceNvmeDrive:test_get_nvme_drive_rawdata_index_out_of_range()
    self.ds.nvme_list = {}
    local cc_str = rpc_service_nvme_drive:get_nvme_drive_rawdata(0)
    lu.assertEquals(cc_str, tostring(ipmi.types.Cc.ParmOutOfRange))
end

function TestRpcServiceNvmeDrive:test_get_nvme_drive_rawdata_success()
    self.ds.nvme_list = {
        {
            get_nvme_info = function()
                return 'RAW_DATA'
            end
        }
    }
    local data = rpc_service_nvme_drive:get_nvme_drive_rawdata(0)
    lu.assertEquals(data, 'RAW_DATA')
end

function TestRpcServiceNvmeDrive:test_send_nvmemi_command_success()
    local nvme_mi_command = require 'nvme.nvme_mi_protocol.nvme_mi_command'
    local orig_send = nvme_mi_command.send_raw_nvme_mi_command
    nvme_mi_command.send_raw_nvme_mi_command = function(_, args)
        return true, 'SQ', 'DATA'
    end

    self.ds.nvme_list = {
        {
            Slot = 0,
            nvme_mi_mctp_obj = { nvme_mi_obj = true }
        }
    }

    local ok, sq, rsp = rpc_service_nvme_drive:send_nvmemi_command(
        '/bmc/kepler/Systems/1/Storage/Drives/Drive_1_0',
        1, 0, 0, 'payload'
    )

    nvme_mi_command.send_raw_nvme_mi_command = orig_send

    lu.assertTrue(ok)
    lu.assertEquals(sq, 'SQ')
    lu.assertEquals(rsp, 'DATA')
end

