Pytest夹具autouse参数利用。True表现会自动在测试中利用,而无需显式指定 ...

打印 上一主题 下一主题

主题 455|帖子 455|积分 1365

1. 全局conftest文件日志记录功能

  1. # 当前路径(使用 abspath 方法可通过dos窗口执行)
  2. current_path = os.path.dirname(os.path.abspath(__file__))
  3. # 上上级目录
  4. ffather_path = os.path.abspath(os.path.join(current_path,"../"))
  5. LOG_FILE_PATH = f'{ffather_path}/log/test.log'
  6. def clear_log_file():
  7.     """Clear the content of the log file."""
  8.     open(LOG_FILE_PATH, 'w').close()
  9. @pytest.fixture(scope='session', autouse=True)
  10. def configure_logging():
  11.     # Clear the log file before starting the tests
  12.     clear_log_file()
  13.     logger = logging.getLogger()
  14.     handler = logging.FileHandler(LOG_FILE_PATH, encoding='utf-8')
  15.     logger.info('Logging configured')
  16.     handler.setLevel(logging.INFO)
  17.     formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  18.     handler.setFormatter(formatter)
  19.     handler.encoding = 'utf-8'
  20.     logger.addHandler(handler)
  21.     logger.setLevel(logging.INFO)
  22.     logging.getLogger().encording = 'utf-8'
  23.     logger.info('Starting test session')
  24.     yield handler
  25.     logger.info('Ending test session')
  26.     logging.getLogger().removeHandler(handler)
  27. def pytest_runtest_makereport(item, call):
  28.     if call.when == 'call' and call.excinfo is not None:
  29.         logging.error(f"Test case failed: {item.nodeid}")
  30.         # ***************以下二选一
  31.         # # 01获取失败的简单内容
  32.         # failure = call.excinfo._getreprcrash()
  33.         # logging.error(failure)
  34.         # 02获取失败的详细信息
  35.         excinfo = call.excinfo
  36.         if excinfo:
  37.             # 格式化异常信息
  38.             formatted_exception = ''.join(traceback.format_exception(excinfo.type, excinfo.value, excinfo.tb))
  39.             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文件配置前置、后置

  1. @pytest.fixture(scope='function')
  2. def connections():
  3.     print('建立连接')
  4.     ssh_client = 'a'
  5.     ssh_server = 'b'
  6.     connections = {
  7.         'c_client':ssh_client,
  8.         's_client':ssh_server
  9.     }
  10.     yield connections
  11.     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.测试用例

  1. import pytest
  2. @pytest.mark.parametrize("title,input,expected", [
  3.     ('title1',1, 2),
  4.     ('title2',2, 4),
  5.     ('title3',3, 6)
  6. ])
  7. class Test_connection1:
  8.     def test_connection1(self,connections,title, input, expected):
  9.         print('\t')
  10.         print(title, input, expected)
  11.         c_conn = connections['c_client']
  12.         s_conn = connections['s_client']
  13.         print(c_conn, s_conn)
  14.         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企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

大连密封材料

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表