pytest.step用法
时间: 2023-12-26 16:28:48 浏览: 23
pytest.step是pytest框架中的一个函数,用于在测试用例中定义测试步骤。它可以帮助我们更好地组织和描述测试用例的执行过程。下面是一个使用pytest.step的示例:
```python
import pytest
def test_demo():
pytest.step("步骤1:执行操作A")
# 执行操作A的代码
pytest.step("步骤2:执行操作B")
# 执行操作B的代码
pytest.step("步骤3:执行操作C")
# 执行操作C的代码
# 断言和其他测试逻辑
assert True
```
在上面的示例中,我们使用pytest.step来定义了三个测试步骤,分别是执行操作A、执行操作B和执行操作C。通过这种方式,我们可以清晰地描述测试用例的执行过程,并且在测试报告中能够看到每个步骤的执行情况。
需要注意的是,pytest.step只是一个用于描述测试步骤的函数,并不会对测试用例的执行产生任何影响。它的作用主要是在测试报告中提供更详细的信息,方便开发人员和测试人员理解和分析测试用例的执行过程。
相关问题
@pytest.mark.parametrize 或者 @pytest.mark.allure.step用法
`@pytest.mark.parametrize` 是 pytest 提供的一个装饰器,可以用于参数化测试用例。它可以让我们在测试用例中使用多组参数来执行同一个测试用例,从而减少测试用例的编写量,提高效率。
示例代码:
```python
import pytest
@pytest.mark.parametrize("input, expected_output", [
(1, 2),
(2, 3),
(3, 4),
(4, 5),
])
def test_increment(input, expected_output):
assert input+1 == expected_output
```
`@pytest.mark.allure.step` 也是 pytest 提供的一个装饰器,用于生成测试报告。它可以将测试用例中的每个步骤作为报告的一个单独的步骤展示,从而更直观地展示测试用例的执行情况。
示例代码:
```python
import pytest
import allure
@allure.step("输入用户名和密码")
def input_username_and_password(username, password):
pass
@allure.step("点击登录按钮")
def click_login_button():
pass
@allure.step("验证登录成功")
def verify_login_success():
pass
def test_login():
input_username_and_password("testuser", "testpass")
click_login_button()
verify_login_success()
```
以上是 `@pytest.mark.parametrize` 和 `@pytest.mark.allure.step` 的基本用法。需要注意的是,`@pytest.mark.allure.step` 需要安装 `pytest-allure-adaptor` 才能正常使用。
pytest yield
pytest中的yield是一个测试框架提供的特殊关键字,用于在测试函数中创建一个生成器。在测试函数中使用yield关键字,可以将测试函数分成多个部分,并在每个部分之间进行一些操作或断言。yield关键字允许在测试函数执行期间暂停和恢复测试,以便更灵活地控制测试流程。
使用yield关键字在pytest中编写测试用例时,可以实现以下效果:
- 在测试函数执行期间可以暂停和恢复测试。
- 在测试函数中可以执行一些准备工作和清理工作。
- 在测试函数中可以断言多个步骤的结果。
下面是一个使用yield的示例代码:
```python
import pytest
def test_example():
# 测试准备工作
setup()
# 第一个测试步骤
yield step1
# 第二个测试步骤
yield step2
# 第三个测试步骤
yield step3
# 测试清理工作
teardown()
```
在上述示例中,test_example函数是一个测试函数。通过使用yield关键字,我们将测试函数分成了多个部分,每个部分对应一个测试步骤。在每个步骤之间,可以执行一些操作或断言。同时,在测试函数开始和结束时,可以执行一些准备工作和清理工作。
注意:yield关键字在pytest中与生成器的常规用法略有不同。它是pytest框架提供的特殊功能,用于控制测试流程。