1. 全局conftest文件日志记录功能
- # 当前路径(使用 abspath 方法可通过dos窗口执行)
- current_path = os.path.dirname(os.path.abspath(__file__))
- # 上上级目录
- ffather_path = os.path.abspath(os.path.join(current_path,"../"))
- LOG_FILE_PATH = f'{ffather_path}/log/test.log'
- def clear_log_file():
- """Clear the content of the log file."""
- open(LOG_FILE_PATH, 'w').close()
- @pytest.fixture(scope='session', autouse=True)
- def configure_logging():
- # Clear the log file before starting the tests
- clear_log_file()
- logger = logging.getLogger()
- handler = logging.FileHandler(LOG_FILE_PATH, encoding='utf-8')
- logger.info('Logging configured')
- handler.setLevel(logging.INFO)
- formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
- handler.setFormatter(formatter)
- handler.encoding = 'utf-8'
- logger.addHandler(handler)
- logger.setLevel(logging.INFO)
- logging.getLogger().encording = 'utf-8'
- logger.info('Starting test session')
- yield handler
- logger.info('Ending test session')
- logging.getLogger().removeHandler(handler)
- def pytest_runtest_makereport(item, call):
- if call.when == 'call' and call.excinfo is not None:
- logging.error(f"Test case failed: {item.nodeid}")
- # ***************以下二选一
- # # 01获取失败的简单内容
- # failure = call.excinfo._getreprcrash()
- # logging.error(failure)
- # 02获取失败的详细信息
- excinfo = call.excinfo
- if excinfo:
- # 格式化异常信息
- formatted_exception = ''.join(traceback.format_exception(excinfo.type, excinfo.value, excinfo.tb))
- logging.error(f"Exception details:\n{formatted_exception}")
复制代码
Python 的日志记录和测试框架 pytest 的配置。以下是具体解释:
- 获取当前路径:
current_path = os.path.dirname(os.path.abspath(__file__))
- 获取上上级目录:
ffather_path = os.path.abspath(os.path.join(current_path,"../"))
- 日志文件路径:
LOG_FILE_PATH = f'{ffather_path}/log/test.log'
- 清空日志文件内容:
def clear_log_file(): """Clear the content of the log file.""" open(LOG_FILE_PATH, 'w').close() 这个函数打开日志文件并清空其内容。
- pytest 测试夹具配置:
scope='session' 表现此夹具在测试会话开始时设置并在会话结束时清理。
autouse=True 表现此夹具会自动在测试中利用,而无需显式指定。
- 处理测试失败并记录具体信息:
pytest_runtest_makereport 钩子用于生成测试陈诉。
假如测试失败(call.when == 'call'),记录测试失败的信息和具体的非常信息。
2.模块conftest.py文件配置前置、后置
- @pytest.fixture(scope='function')
- def connections():
- print('建立连接')
- ssh_client = 'a'
- ssh_server = 'b'
- connections = {
- 'c_client':ssh_client,
- 's_client':ssh_server
- }
- yield connections
- print('断开连接')
复制代码
这段代码展示了如何利用 pytest 的夹具(fixtures)来设置和清理测试环境。夹具是 pytest 提供的一种机制,用于提供测试所需的前置条件和后置处理。具体解释如下:
- import pytest:导入 pytest 库,提供了测试框架和夹具功能。
- @pytest.fixture(scope='function'):这是 pytest 的夹具装饰器,用于定义一个夹具。夹具是测试实行前和后进行准备和清理的代码块。
- scope='function':指定夹具的作用范围。在这里,scope='function' 表现每个测试函数都会调用一次该夹具。每次测试函数调用夹具时,夹具都会实行一次准备和清理代码。其他可选的作用范围包罗 'module'(模块级别)、'class'(类级别)和 'session'(会话级别)。
- def connections()::定义一个名为 connections 的夹具函数。
- print('建立毗连'):在夹具实行时,打印一条消息,表现正在建立毗连。这个步调用于模拟或现实创建测试所需的资源或状态。
- ssh_client = 'a' 和 ssh_server = 'b':模拟创建两个毗连对象(ssh_client 和 ssh_server)。在现实的测试中,这里可能会用现实的毗连对象或资源初始化代码。
- connections = {'c_client': ssh_client, 's_client': ssh_server}:将这些毗连对象放入一个字典中,并将字典命名为 connections。这个字典作为夹具的返回值,将被提供给需要它的测试函数。
- yield connections:将 connections 字典作为夹具的返回值提供给测试函数。yield 语句表现夹具的“前置准备”部分结束了,接下来是“后置清理”部分的代码。
- print('断开毗连'):在所有利用此夹具的测试函数实行完毕后,打印一条消息,表现正在断开毗连。这是夹具的“后置清理”部分,用于清理测试资源或状态。在现实利用中,这里可能包罗关闭毗连或释放资源的代码。
3.测试用例
- import pytest
- @pytest.mark.parametrize("title,input,expected", [
- ('title1',1, 2),
- ('title2',2, 4),
- ('title3',3, 6)
- ])
- class Test_connection1:
- def test_connection1(self,connections,title, input, expected):
- print('\t')
- print(title, input, expected)
- c_conn = connections['c_client']
- s_conn = connections['s_client']
- print(c_conn, s_conn)
- assert 1==1
复制代码
- import pytest:导入 pytest 库,用于编写和实行测试。
- @pytest.mark.parametrize("title,input,expected", [...]):这是 pytest 的参数化装饰器,用于将多个输入值通报给测试方法。参数化使得同一测试方法可以利用不同的输入数据运行多次,以确保方法在各种环境下都能正常工作。
- "title,input,expected":指定参数名称。
- [...]:定义了三组测试数据:
- ('title1', 1, 2)
- ('title2', 2, 4)
- ('title3', 3, 6)
- class Test_connection1:定义了一个测试类 Test_connection1,用于组织测试方法。测试方法会被应用于类中的每个测试用例。
- def test_connection1(self, connections, title, input, expected)::这是测试方法 test_connection1。该方法将会接收由参数化装饰器提供的参数 title、input 和 expected,以及 connections 夹具。
- connections:这是 pytest 的夹具,提供了测试所需的毗连对象。
- title, input, expected:来自参数化装饰器的参数值。
- print('\t'):打印一个制表符,用于输出格式化。
- print(title, input, expected):打印测试用例的当前参数值,帮助调试和验证测试数据。
- c_conn = connections['c_client'] 和 s_conn = connections['s_client']:从 connections 夹具中提取 c_client 和 s_client 毗连对象,并赋值给变量 c_conn 和 s_conn。
- print(c_conn, s_conn):打印提取的毗连对象,用于检查其值。
- assert 1 == 1:一个基本的断言,用于确保测试运行时不会失败。现实测试中会用复杂的断言来验证 input 和 expected 是否符合预期。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |