关键字 开发-14 用例跳过

发布时间 2023-12-26 10:35:48作者: dack_deng

前言

有些情况需要通过加入用例步骤之间的等待时间,来进行接口的断言或者后置,其次有时候需要根据条件判断用例是否需要执行。

1. 加入sleep等待时间

通过sleep关键字即可实现,在执行用例的过程前添加等待时间。

                        elif item == 'sleep':
                            try:
                                sleep_value = render_template_obj.rend_template_any(value, **self.context)
                                log.info(f'sleep time: {sleep_value}')
                                time.sleep(sleep_value)
                            except Exception as msg:
                                log.error(f'Run error: sleep value must be int or float, error msg: {msg}')
# testcase

config:
  name: 登录用例
  variables:
    username: "admin"
    password: "eaton@2023"

teststeps:
  -
    name: 登录-步骤1
    sleep: 3
    api: api/login.yml
    extract:
      code1: $.code
      code2: body.code
      token: $.data.token
    validate:
      - eq: [$.code, "000000"]
      - eq: [status_code, 200]

  -
    name: 登录-步骤2
    sleep: 3
    api: api/login.yml
    validate:
      - eq: [ status_code, 200 ]

在yaml文件中,支持每个步骤之间的等待,运行pytest ./testcase,可以知道一条用例,步骤一和步骤二同时加了3秒,于是功运行了6秒多的时间。

2. skip跳过用例

pytest 实现跳过用例有2种方式。

# 方式一,在testcase中添加@pytest.mark.skip装饰器
@pytest.mark.skip(reason="no way of currently testing this")
def test_the_unknown():
...

# 方式二,pytest.skip(skip_reason)是一个pytest框架中的函数,用于告诉pytest跳过当前测试用例。当某些条件不满足或者测试用例暂时不可用时,可以使用pytest.skip()来指示pytest跳过执行当前测试用例,并在报告中显示跳过的原因。
import pytest

def test_function():
    if some_condition_not_met:
        pytest.skip("Skipping this test because some_condition_not_met is True")
    # 测试代码

于是在用例执行的前面,添加skip关键字。

                        elif item == 'skip':
                            skip_reason = render_template_obj.rend_template_any(value, **step_context)
                            pytest.skip(skip_reason)
# testcase/test_login.yml
config:
  name: 登录用例
  variables:
    username: "admin"
    password: "eaton@2023"

teststeps:
  -
    name: 登录-步骤1
    skip: 测试数据不足,暂时不测试
    api: api/login.yml
    extract:
      code1: $.code
      code2: body.code
      token: $.data.token
    validate:
      - eq: [$.code, "000000"]
      - eq: [status_code, 200]

3. skipif条件满足跳过

skipif关键字可以参考skip关键字即可,只需要加一个if条件判断即可。

                        elif item == 'skipif':
                            if_exp = render_template_obj.rend_template_any(value, **step_context)
                            log.info(f'skipif : {eval(str(if_exp))}')
                            if eval(str(if_exp)):  # 只需加一个if条件,下面同样用到的也是pytest.skip()
                                pytest.skip(str(if_exp))
config:
  name: 登录用例
  variables:
    username: "admin"
    password: "eaton@2023"

teststeps:
  -
    name: 登录-步骤1
    skipif: 100 > 50  # 条件满足,则跳过
    api: api/login.yml
    extract:
      code1: $.code
      code2: body.code
      token: $.data.token
    validate:
      - eq: [$.code, "000000"]
      - eq: [status_code, 200]