-- 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 utils = require 'power_mgmt_utils'
local export_import_engine = require 'export_import_engine'
local c_psu_object = require 'device.psu'
local psu_service = require 'psu_service'

local psu = {
    set_work_mode = function()end,
    IsUpgrading = false,
    Protocol = 'pmbus',
    is_healthy = function() return true end,
    power_upgrade = function() return 201 end,
    get_all_prop_names = function (self)
        local prop_names = {}
        for key, value in pairs(self) do
            local value_type = type(value)
            if value_type == 'string' or value_type == 'number' or
                value_type == 'boolean' or value_type == 'table' then
                table.insert(prop_names, key)
            end
        end
        return prop_names
    end
}
psu.__index = psu

if not c_psu_object.collection then
    c_psu_object.collection = {}
end

c_psu_object.collection.objects = {
    setmetatable({
        SlotNumber = 1, ps_id = 1, ObjectName = 'PSU1', tb = {test = 1},
        path = 1, InputPowerWatts = 88, OutputPowerWatts = 66,
        power_upgrade = function() return 203 end
    }, {__index = psu}),
    setmetatable({SlotNumber = 2, ps_id = 2, ObjectName = 'PSU1'}, {__index = psu})
}

-- 为 psu_service.dump_obj_infos 提供简单的 fold 实现
if not c_psu_object.collection.fold then
    c_psu_object.collection.fold = function (_, fn)
        for _, obj in ipairs(c_psu_object.collection.objects or {}) do
            fn(nil, obj)
        end
    end
end

TestExportImport = {}

function TestExportImport:test_export()
    local ok = pcall(function ()
        export_import_engine.export({})
    end)
    lu.assertTrue(ok)
end

function TestExportImport:test_import()
    local ok = pcall(function ()
        export_import_engine.import({}, '{}')
    end)
    lu.assertTrue(ok)
end

function TestExportImport:test_log_dump()
    local fp = {
        write = function()end
    }
    -- 为 dump_obj_infos 临时打桩 fold，只遍历本文件构造的 PSU 对象
    local old_fold = c_psu_object.collection.fold
    c_psu_object.collection.fold = function (_, fn)
        for _, obj in ipairs(c_psu_object.collection.objects or {}) do
            if obj.ps_id and obj.ObjectName then
                fn(nil, obj)
            end
        end
    end

    local ok = pcall(function ()
        psu_service:dump_obj_infos(fp)
    end)

    c_psu_object.collection.fold = old_fold
    lu.assertTrue(ok)
end
