# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved.
# MindIE 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.

"""v2 P5+ 安全网:OLC 自动初始化兜底测试

验证:未显式调用 OLC.get_instance() 的情况下,
直接调用 process / async_process 会自动触发初始化。
"""
import asyncio
import unittest
from unittest.mock import MagicMock, patch

from olc.olc import OLC


def _arun(coro):
    return asyncio.new_event_loop().run_until_complete(coro)


class TestAutoInitialization(unittest.TestCase):

    def setUp(self):
        # 备份并清空单例,让测试能验证"首次调用"的自动初始化行为
        self._saved_instance = OLC._instance
        OLC._instance = None

    def tearDown(self):
        OLC._instance = self._saved_instance

    def test_process_auto_initializes_when_not_initialized(self):
        """直接调 process(),应该自动触发 init"""
        with patch.object(OLC, "get_instance", wraps=OLC.get_instance) as spy:
            request = MagicMock()
            request.tags = {}
            request.token_number = 1
            OLC.process(request)
            self.assertGreaterEqual(spy.call_count, 1)
        self.assertIsNotNone(OLC._instance, "OLC._instance 应该被自动初始化填充")

    def test_async_process_auto_initializes(self):
        """直接 await async_process(),应该自动触发 init(且不阻塞事件循环)"""

        async def go():
            request = MagicMock()
            request.tags = {}
            request.token_number = 1
            await OLC.async_process(request)

        _arun(go())
        self.assertIsNotNone(OLC._instance)


if __name__ == "__main__":
    unittest.main(verbosity=2)