0
点赞
收藏
分享

微信扫一扫

Python知识点:如何使用Pytest进行单元测试

小迁不秃头 2024-09-06 阅读 21
python

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 的配置。以下是详细解释:

  1. 获取当前路径

    current_path = os.path.dirname(os.path.abspath(__file__))
  2. 获取上上级目录

    ffather_path = os.path.abspath(os.path.join(current_path,"../"))
  3. 日志文件路径

    LOG_FILE_PATH = f'{ffather_path}/log/test.log'
  4. 清空日志文件内容

    def clear_log_file(): """Clear the content of the log file.""" open(LOG_FILE_PATH, 'w').close()

    这个函数打开日志文件并清空其内容。

  5. pytest 测试夹具配置

  6. 处理测试失败并记录详细信息

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 提供的一种机制,用于提供测试所需的前置条件和后置处理。详细解释如下:

  1. import pytest:导入 pytest 库,提供了测试框架和夹具功能。

  2. @pytest.fixture(scope='function'):这是 pytest 的夹具装饰器,用于定义一个夹具。夹具是测试执行前和后进行准备和清理的代码块。

    • scope='function':指定夹具的作用范围。在这里,scope='function' 表示每个测试函数都会调用一次该夹具。每次测试函数调用夹具时,夹具都会执行一次准备和清理代码。其他可选的作用范围包括 'module'(模块级别)、'class'(类级别)和 'session'(会话级别)。
  3. def connections()::定义一个名为 connections 的夹具函数。

  4. print('建立连接'):在夹具执行时,打印一条消息,表示正在建立连接。这个步骤用于模拟或实际创建测试所需的资源或状态。

  5. ssh_client = 'a'ssh_server = 'b':模拟创建两个连接对象(ssh_clientssh_server)。在实际的测试中,这里可能会用实际的连接对象或资源初始化代码。

  6. connections = {'c_client': ssh_client, 's_client': ssh_server}:将这些连接对象放入一个字典中,并将字典命名为 connections。这个字典作为夹具的返回值,将被提供给需要它的测试函数。

  7. yield connections:将 connections 字典作为夹具的返回值提供给测试函数。yield 语句表示夹具的“前置准备”部分结束了,接下来是“后置清理”部分的代码。

  8. 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
  1. import pytest:导入 pytest 库,用于编写和执行测试。

  2. @pytest.mark.parametrize("title,input,expected", [...]):这是 pytest 的参数化装饰器,用于将多个输入值传递给测试方法。参数化使得同一测试方法可以使用不同的输入数据运行多次,以确保方法在各种情况下都能正常工作。

    • "title,input,expected":指定参数名称。
    • [...]:定义了三组测试数据:
      • ('title1', 1, 2)
      • ('title2', 2, 4)
      • ('title3', 3, 6)
  3. class Test_connection1:定义了一个测试类 Test_connection1,用于组织测试方法。测试方法会被应用于类中的每个测试用例。

  4. def test_connection1(self, connections, title, input, expected)::这是测试方法 test_connection1。该方法将会接收由参数化装饰器提供的参数 titleinputexpected,以及 connections 夹具。

    • connections:这是 pytest 的夹具,提供了测试所需的连接对象。
    • title, input, expected:来自参数化装饰器的参数值。
  5. print('\t'):打印一个制表符,用于输出格式化。

  6. print(title, input, expected):打印测试用例的当前参数值,帮助调试和验证测试数据。

  7. c_conn = connections['c_client']s_conn = connections['s_client']:从 connections 夹具中提取 c_clients_client 连接对象,并赋值给变量 c_conns_conn

  8. print(c_conn, s_conn):打印提取的连接对象,用于检查其值。

  9. assert 1 == 1:一个基本的断言,用于确保测试运行时不会失败。实际测试中会用复杂的断言来验证 inputexpected 是否符合预期。

举报

相关推荐

0 条评论