-- 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_fan_group_object = require 'fan_group_object'
local c_object_manage = require 'mc.orm.object_manage'
local c_tasks = require 'mc.orm.tasks'
local thermal_db = require 'thermal_mgmt.db'
local hook_tasks = require 'test_common.hook_tasks'
local test_utils = require 'test_utils'

TestFanGroup = {}

function TestFanGroup:flush()
    c_tasks.get_instance():run_all_task()
    self.database.db:flush()
end

function TestFanGroup:setUp()
    self.database = thermal_db(':memory:')

    hook_tasks.hook()
    self.object_manage = c_object_manage.new(self.database)
    self.object_manage.app = self

    local fan_group  = {
        Id = 1,
        FanSlots = {1, 2, 3, 4},
        SpeedPercent = 30
    }

    local fans_obj = test_utils.add_fan_group_obj(self.object_manage, 'Fans_1', fan_group)
    self.object_manage.mc:before_add_object(c_fan_group_object.__class_name, fans_obj)
    self.object_manage.mc:add_object(c_fan_group_object.__class_name, fans_obj, '010107')
    self.object_manage.mc:prepare_ok()
    self:flush()
end

function TestFanGroup:tearDown()
    c_object_manage.destroy()
    self.database.db:close()
    hook_tasks.unhook()
end

function TestFanGroup:test_roperty_before_change_callback()
    local level_range = {20, 100}
    local props = {
        EXPECTED_SPEED_PERCENT = 'ExpectedSpeedPercent'
    }
    local obj = c_fan_group_object.collection:find({
        Id = 1,
    })
    lu.assertEquals(obj:property_before_change_callback('ExpectedSpeedPercent', 30, level_range, nil), true)
    lu.assertErrorMsgContains("PropertyValueOutOfRange", function()
        obj:property_before_change_callback('ExpectedSpeedPercent', 10, level_range, nil)
    end)
    local level_range = {2}
    lu.assertErrorMsgContains("PropertyValueLengthOutOfRange", function()
        obj:property_before_change_callback('ExpectedSpeedPercent', 30, level_range, nil)
    end)
end

function TestFanGroup:test_fan_group_ctor_init()
    local obj = c_fan_group_object.collection:find({
        Id = 1,
    })
    lu.assertEquals(obj.SpeedPercent, 30)
    lu.assertIsTable(obj.FanSlots)
end
