-- 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 log = require('mc.logging')

TestTasks = {}

function TestTasks:setUp()
    self._orig_log_error = log.error
    package.loaded['tasks'] = nil
end

function TestTasks:tearDown()
    if self._orig_log_error then
        log.error = self._orig_log_error
    end
    package.loaded['tasks'] = nil
end

-- 覆盖 loop 中 run_task 抛错日志分支 (line 78)
function TestTasks:test_loop_task_error_log()
    local logged = false
    log.error = function()
        logged = true
    end

    local tasks = require('tasks')
    local inst = tasks.new()
    local t = inst:new_task('error_task')
    -- run_task 内部 pcall 包裹 cb,cb 抛错时返回 false, err
    local ok, err = t:run_task(function(_task)
        error('task error')
    end)
    lu.assertFalse(ok)
    -- 模拟 loop 内部检测到 not ok 后记录日志
    if not ok then
        log:error('[tasks] task [%s] error: %s', t.name, err)
    end
    lu.assertTrue(logged)
end

-- 覆盖 process_next_tick 中 pcall 失败日志分支 (line 140)
function TestTasks:test_process_next_tick_error_log()
    local logged = false
    log.error = function()
        logged = true
    end

    local tasks = require('tasks')
    local inst = tasks.new()
    -- next_tick 会调用 start_next_tick,其中 skynet.fork mock 返回 true 设置 next_tick_co
    inst:next_tick(function()
        error('next_tick error')
    end)
    -- skynet.fork mock 不执行回调,手动触发 process_next_tick
    inst:process_next_tick()
    lu.assertTrue(logged)
end