Skip to content

Commit

Permalink
test单测文件更改 (#285)
Browse files Browse the repository at this point in the history
* add test
---------

Co-authored-by: yinjiaqi <yinjiaqi@baidu.com>
  • Loading branch information
C9luster and yinjiaqi committed Apr 29, 2024
1 parent 890281f commit 0376896
Show file tree
Hide file tree
Showing 30 changed files with 407 additions and 244 deletions.
36 changes: 34 additions & 2 deletions appbuilder/tests/parallel_ut_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.


# add test
import os
import sys
import multiprocessing
Expand Down Expand Up @@ -145,6 +147,16 @@ def pull_last_n_log(ut_context, file_name, line_count=80):


def run_sync_unittest(test_file):
"""
同步运行单元测试
Args:
test_file (str): 测试文件名
Returns:
dict: 包含进程对象、日志文件对象以及开始时间的字典
"""
default_env = os.environ.copy()
current_env = copy.copy(default_env)
cmd = COVERAGE_CMD + [test_file]
Expand Down Expand Up @@ -188,7 +200,6 @@ def run_async_unittest(test_file, case_idx, case_num, timeout=1200):
case_idx, case_num, end_time - begin_time, test_file,))
return


def parallel_execute_unittest(test_cases, parallel_num=2):
case_num = len(test_cases)
success_cases = []
Expand Down Expand Up @@ -267,6 +278,17 @@ def run_cpu_parallel_unittest():


def run_cpu_serial_unittest():
"""
运行CPU_SERIAL模式下的单元测试,包括并行和串行两种方式,记录并打印成功和失败的情况及耗时
Args:
Returns:
success_cases (list): 成功运行的测试用例列表
failed_cases (list): 失败运行的测试用例列表
total_time (float): 运行总耗时(单位:秒)
"""
os.environ["TEST_CASE"] = "CPU_SERIAL"
logger.info("\n================ CPU_SERIAL ================\n")

Expand Down Expand Up @@ -347,6 +369,16 @@ def run_unknown_unittest():


def create_unittest_report():
"""
生成单元测试报告。
Args:
无。
Returns:
无返回值。
"""
# 创建日志目录
if not os.path.exists("./ut_logs"):
os.mkdir("./ut_logs")
Expand All @@ -363,7 +395,7 @@ def create_unittest_report():
total_success_cases += success_cases
total_failed_cases += failed_cases
total_ut_time += suite_time

logger.info("============== Summary Report =============")
logger.info("\nCI运行结束,总耗时:{}".format(total_ut_time))
if len(total_failed_cases) != 0:
Expand Down
2 changes: 1 addition & 1 deletion appbuilder/tests/test_animal_recognize.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import appbuilder
import os

@unittest.skip("Cannot connect to proxy.")
@unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "")
class TestAnimalRecognition(unittest.TestCase):
def setUp(self):
"""
Expand Down
49 changes: 49 additions & 0 deletions appbuilder/tests/test_appbuilder_core_components_retriever.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Copyright (c) 2023 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import unittest
import subprocess
import sys
import time

from appbuilder.core.components.retriever.baidu_vdb.baiduvdb_retriever import _try_import,BaiduVDBVectorStoreIndex


@unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "")
class TestAppbuilderCoreComponentsRetriever__try_import(unittest.TestCase):
def test_baidu_vdb_baiduvdb_retriever_try_import(self):
subprocess.check_call([sys.executable, "-m", "pip", "uninstall", "-y", "pymochow"])
with self.assertRaises(ImportError):
_try_import()
subprocess.check_call([sys.executable, "-m", "pip", "install", "pymochow"])
_try_import()


def test_baidu_vdb_baiduvdb_retriever_BaiduVDBVectorStoreIndex(self):
# test not isinstance(instance_id, str):
with self.assertRaises(TypeError):
BaiduVDBVectorStoreIndex(
instance_id = 1,
api_key="key",
)
# test not isinstance(api_key, str):
with self.assertRaises(TypeError):
BaiduVDBVectorStoreIndex(
instance_id = "test",
api_key=1,
)


if __name__ == '__main__':
unittest.main()
2 changes: 1 addition & 1 deletion appbuilder/tests/test_console_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import unittest
import appbuilder

@unittest.skip("current Number of datasets over max_nums_datasets:50")
@unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "")
class TestDataset(unittest.TestCase):

@classmethod
Expand Down
40 changes: 40 additions & 0 deletions appbuilder/tests/test_core_console_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Copyright (c) 2023 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import unittest

from appbuilder.core.console.base import ConsoleLLMMessage,ConsoleCompletionResponse
from appbuilder.core._exception import AppBuilderServerException
from appbuilder.core.components.llms.base import CompletionResponse, LLMMessage
from appbuilder.core.message import Message


# @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "")
@unittest.skip(reason="暂时跳过")
class TestCoreConsoleBase(unittest.TestCase):
def test_ConsoleLLMMessage_init(self):
message=Message()
llmMessage=LLMMessage(message)
clm=ConsoleLLMMessage(llmMessage)
self.assertIsInstance(clm,ConsoleLLMMessage)

def test_ConsoleCompletionResponse_init(self):
# 测试stream=True
cr=CompletionResponse()
ccr=ConsoleCompletionResponse(response=cr,stream=True)



if __name__ == '__main__':
unittest.main()
83 changes: 83 additions & 0 deletions appbuilder/tests/test_core_user_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Copyright (c) 2023 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import os
import uuid

from appbuilder.core.user_session import UserSession,SessionMessage
from appbuilder.core.context import init_context,_LOCAL_KEY,get_context,context_var
from appbuilder.core.message import Message


@unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "")
class TestCoreUserSession(unittest.TestCase):
def test_usersession_init(self):
UserSession._instance = None
UserSession._initialized = False
with self.assertRaises(ValueError):
user_session=UserSession(user_session_config=1234)
UserSession._instance = None
UserSession._initialized = False

def test_get_context(self):
context_var=0
ctx=get_context()

# 测试not ctx.session_id.startswith(_LOCAL_KEY)
def test_not_startswith_LOCAL_KEY(self):
user_session = UserSession()
init_context(
session_id=str(uuid.uuid4()),
request_id=str(uuid.uuid4())
)
key = "test_key"
message_dict = {key: Message(content={"key": "value"})}
# if key not in ctx.session_vars_dict
user_session.append(message_dict)
history = user_session.get_history(key)
self.assertEqual(len(history), 0)
# if not isinstance(message, Message)
with self.assertRaises(ValueError):
user_session.append({key: "test"})
# 测试if key in ctx.session_vars_dict
with self.assertRaises(KeyError):
user_session.append(message_dict)
# 测试_post_append(self)的try
user_session._post_append()


# 测试ctx.session_id.startswith(_LOCAL_KEY)
def test_startswith_LOCAL_KEY(self):
user_session = UserSession()
init_context(
session_id=_LOCAL_KEY+str(uuid.uuid4()),
request_id=_LOCAL_KEY+str(uuid.uuid4())
)
key = "test_key"
message_dict = {key: Message(content={"key": "value"})}
# if key not in ctx.session_vars_dict
user_session.append(message_dict)
history = user_session.get_history("test")
self.assertEqual(len(history), 0)
history = user_session.get_history(key)
self.assertEqual(len(history), 1)
# if not isinstance(message, Message)
with self.assertRaises(ValueError):
user_session.append({key: "test"})
# 测试_post_append(self)的异常
with self.assertRaises(Exception):
user_session._post_append()

if __name__ == '__main__':
unittest.main()
74 changes: 74 additions & 0 deletions appbuilder/tests/test_core_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Copyright (c) 2023 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import os
import base64

import appbuilder.core.utils as ut
from appbuilder.utils.sse_util import SSEClient,Event



@unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "")
class TestCoreUtils(unittest.TestCase):
def test_utils_get_user_agent(self):
user_agent=ut.utils_get_user_agent()

def test_get_model_list(self):
from appbuilder.core._exception import TypeNotSupportedException
with self.assertRaises(TypeNotSupportedException):
model_list=ut.get_model_list(api_type_filter=["unknown"])

def test_convert_cloudhub_url(self):
try:
from appbuilder.core._client import HTTPClient
except:
pass
with self.assertRaises(ValueError):
url=ut.convert_cloudhub_url(client=HTTPClient,qianfan_url="unknown")

def test_is_url(self):
is_url=ut.is_url("unknown")

# def test_utils_sse_uti_events(self):
# binary_data = os.urandom(100) # 生成100字节的随机数据
# encoded_data = base64.b64encode(binary_data).decode('utf-8')
# sseClient=SSEClient(event_source=encoded_data)
# sseClient.events()

# def test_utils_sse_uti_events(self):
# binary_data = os.urandom(100) # 生成100字节的随机数据
# encoded_data = base64.b64encode(binary_data).decode('utf-8')
# sseClient=SSEClient(event_source=encoded_data)
# sseClient.close()

def test_utils_sse_uti_Events(self):
event_null_data=Event(id="id")
s=event_null_data.debug_str
event=Event(id="id",data='data',retry="retry")
s=event.debug_str
event.raw="raw"
s_change_raw=event.debug_str


if __name__ == '__main__':
unittest.main()








9 changes: 4 additions & 5 deletions appbuilder/tests/test_dialog_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import unittest
import appbuilder

@unittest.skip("AssertionError: False is not true")
@unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "")
class TestDialogSummary(unittest.TestCase):
def setUp(self):
"""
Expand Down Expand Up @@ -49,13 +49,12 @@ def test_run_with_model_names(self):
"""测试不同的 stream 和 temperature 参数值"""

chats = appbuilder.get_model_list(api_type_filter=["chat"])
self.assertTrue("ERNIE Speed-AppBuilder专用版" in chats)
self.assertTrue("EB-turbo-AppBuilder专用版" in chats)

appbuilder.DialogSummary(model="ERNIE Speed-AppBuilder专用版")
appbuilder.DialogSummary(model="EB-turbo-AppBuilder专用版")

with self.assertRaises(Exception):
appbuilder.DialogSummary(model="ERNIE Speed-AppBuilder-None")

appbuilder.DialogSummary(model="")

if __name__ == '__main__':
unittest.main()
1 change: 1 addition & 0 deletions appbuilder/tests/test_doc_crop_enhance.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ def test_run_with_timeout_and_retry(self):
None
"""
# 定义一个图片URL
image_url = "https://bj.bcebos.com/v1/appbuilder/doc_enhance_test.png?" \
"authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01" \
"-24T12%3A51%3A09Z%2F-1%2Fhost%2F2020d2433da471b40dafa933d557a1e" \
Expand Down
Loading

0 comments on commit 0376896

Please sign in to comment.