Pytest-配置文件

本文详细介绍了pytest配置文件pytest.ini的设置方法,包括如何配置命令行参数、测试搜索路径、测试文件名、测试类名及测试函数名,帮助读者掌握pytest的高级用法。

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

  • 例如:
    [pytest]
    
    addopts = -s
    
    testpaths = ./scripts
    
    python_files = test_*.py
    
    python_classes = Test_*
    
    python_functions = test_*
     
    pytest的配置文件通常放在测试目录下,名称为pytest.ini,命令行运行时会使用该配置文件中的配置.
  • 配置pytest命令行运行参数
    [pytest]
    addopts = -s ... # 空格分隔,可添加多个命令行参数 -所有参数均为插件包的参数

 

  • 配置测试搜索的路径
    [pytest]
    testpaths = ./scripts  # 当前目录下的scripts文件夹 -可自定义

 

  • 配置测试搜索的文件名
    [pytest]
    python_files = test_*.py  
    # 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件 -可自定义
  • 配置测试搜索的测试类名
    [pytest]
    python_classes = Test_*  
    # 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件中,以Test_开头的类 -可自定义

 

  • 配置测试搜索的测试函数名
    [pytest]
    python_functions = test_*  
    # 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件中,以Test_开头的类内,以test_开头的方法 -可自定义

 

 

 

 

 

 

 

 

 

 

 

 

### 如何配置 `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、付费专栏及课程。

余额充值