-- 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.
-- See the Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2

local lu = require('luaunit')

local task_mgmt = require('mc.mdb.task_mgmt')
local log = require('mc.logging')
local skynet = require('skynet')

TestTaskService = {}

function TestTaskService:setUp()
    self._orig_create_task = task_mgmt.create_task
    self._orig_update_task = task_mgmt.update_task
    self._orig_get_task_obj = task_mgmt.get_task_obj
    self._orig_destroy_task = task_mgmt.destroy_task
    self._orig_log_error = log.error
    self._orig_log_notice = log.notice
    self._orig_timeout = skynet.timeout
end

function TestTaskService:tearDown()
    if self._orig_create_task then
        task_mgmt.create_task = self._orig_create_task
    end
    if self._orig_update_task then
        task_mgmt.update_task = self._orig_update_task
    end
    if self._orig_get_task_obj then
        task_mgmt.get_task_obj = self._orig_get_task_obj
    end
    if self._orig_destroy_task then
        task_mgmt.destroy_task = self._orig_destroy_task
    end
    if self._orig_log_error then
        log.error = self._orig_log_error
    end
    if self._orig_log_notice then
        log.notice = self._orig_log_notice
    end
    if self._orig_timeout then
        skynet.timeout = self._orig_timeout
    end
    package.loaded['task_service'] = nil
end

-- 覆盖 create:创建任务失败触发日志分支 (line 35)
function TestTaskService:test_create_task_failed_with_err_code()
    local logged = false
    task_mgmt.create_task = function()
        return -1, 'task_busy', nil
    end
    log.error = function()
        logged = true
    end
    skynet.timeout = function() end

    local task_service = require('task_service')
    local ok = pcall(task_service.create, {}, 'TaskName', '/path')
    lu.assertFalse(ok)
    lu.assertTrue(logged)
end

-- 覆盖 create:创建任务成功
function TestTaskService:test_create_task_success()
    task_mgmt.create_task = function()
        return task_mgmt.create_code.TASK_CREATE_SUCCESSFUL, nil, 456
    end
    task_mgmt.get_task_obj = function()
        return {}
    end
    skynet.timeout = function() end
    log.notice = function() end

    local task_service = require('task_service')
    local task_id = task_service.create({}, 'TaskName', '/path')
    lu.assertEquals(task_id, 456)
end

-- 覆盖 update:更新任务失败日志分支
function TestTaskService:test_update_task_failed()
    local logged = false
    task_mgmt.update_task = function()
        return -1
    end
    log.error = function()
        logged = true
    end

    local task_service = require('task_service')
    task_service.update(1, task_mgmt.state.Running, task_mgmt.status.OK)
    lu.assertTrue(logged)
end