pytest-配置文件

pytest.ini是pytest的配置核心,用于调整默认行为。它可以设置命令行选项如-v和-s,注册标记避免拼写错误,指定最小版本,忽略特定目录,定义测试路径,改变搜索规则,以及配置日志输出。通过这些配置,你可以更加高效地管理和运行测试用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pytest配置文件简介

pytest.ini是pytest的主配置文件,可以改变pytest的默认行为

如何配置pytest

更改默认命令行选项

对于一些常用的命令行参数,比如-v,-s,经常使用,但是又不想重复输入,可以在pytest.ini文件的addopts来设置

[pytest]
addopts=-v -s
注册标记来防范拼写错误

我们可以自定义标记来管理测试用例,比如给冒烟测试用例标记为@pytest.mark.smoke,可以在配置文件里注册标记来避免拼写错误,没有注册的标记会提示warning
makers格式是line list

[pytest]
addopts=-v -s
markers=
smoke
regession
指定pytest的最低版本

minversion=3.0

指定pytest忽略某些目录

norecurse

指定测试目录

使用testpaths指定pytest访问哪个目录
只有在pytest未指定文件目录参数或测试用例标识符时,该选项才会启用

### 如何配置 `pytest-bdd` 设置文件 为了使 `pytest-bdd` 能够正常工作并与其他工具集成,通常需要在项目的根目录下创建一个名为 `conftest.py` 的配置文件。此文件用于定义全局的 fixture 和其他配置项。 #### 创建 `conftest.py` ```python import pytest from selenium import webdriver from pytest_bdd import given, when, then, scenario @pytest.fixture(scope="session") def browser(): """Initialize and provide a Selenium WebDriver instance.""" driver = webdriver.Chrome() yield driver driver.quit() @given('I am on the homepage') def i_am_on_the_homepage(browser): browser.get("http://example.com") @when('I navigate to "{section}" section') def i_navigate_to_section(browser, section): link = browser.find_element_by_link_text(section) link.click() @then('the title should be "{expected_title}"') def check_page_title(browser, expected_title): assert browser.title == expected_title ``` 上述代码展示了如何通过 `conftest.py` 来初始化浏览器实例以及定义一些基本的操作函数[^1]。 #### 定义 BDD 测试场景 除了 `conftest.py` 外,在测试目录中还需要有 `.feature` 文件来描述具体的业务逻辑和预期行为: ```gherkin Feature: User Navigation Scenario Outline: Navigate through sections of website Given I am on the homepage When I navigate to "<section>" section Then the title should be "<title>" Examples: | section | title | | About | About Example Domain| | Services | Our Services | | Contact Us | Get In Touch | ``` 这段 Gherkin 文本用来指定不同页面之间的导航路径及其对应的标题验证[^4]。 #### 执行测试 完成以上两部分之后就可以执行测试了。只需简单地运行 `pytest` 命令即可自动发现所有的 feature 文件并按照给定的 step definitions 进行匹配处理[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值