pytest官网:https://docs.pytest.org/en/stable/

pytest和unittest都是python的测试框架,但是pytest相比于unittest,又有以下特点:

  • 增加了标记功能
  • 有丰富的插件库,目前有800+ (点击跳转插件地址
  • 增加了fixture(可以设置会话级、模块级、类级、函数级的fixture)
  • 自动发现测试模块和测试方法
  • 断言方式为 assert 表达式 即可。(更加自由,表达式可以有逻辑运算可以是函数返回值)

【备注】

会话级:整个自动化用例运行过程中只执行一次的事情

模块级:py文件

类级:例如unittest中setUpClass和tearDownClass完成的事情

函数级:即用例级别,例如unittest中setUp和tearDown完成的事情

1、安装(-U即--upgrade,意思是如果已安装,则升级到最新版)

pip install -U pytest

2、检查安装是否成功

$ pytest --version
pytest 6.1.2

 

pytest自动收集测试用例的规则

1、在哪个目录下运行pytest命令,则在那个目录下搜索测试用例

2、test_*.py文件 或者 *_test.py 文件中:

(1)以test_*开头的函数名

(2)以Test开头的测试类(不能有__init__函数)中,以test_*开头的函数

上述(1)(2)是或的关系。因为py文件中可以直接写函数,或者先写类,再在类中写函数。

pytest标记

在测试用例/测试类前面加上: @pytest.mark.标记名

可以在一个用例上面加多个标记。标记名可以自己取。

@pytest.mark.main  #该类下的所有用例都有该标记
class TestLogin:

  @pytest.mark.demo   @pytest.mark.smoke
  @pytest.mark.skip
  def test_login_success():     pass
  def test_login_success():
    pass

 

pytest命令

$ pytest  #直接收集用例并执行
$ pytest --help  #帮助
$ pytest -m smoke  #仅执行标记了smoke的测试用例

 执行命令:

-q  :更简洁的报告模式。Execute the test function with “quiet” reporting mode。

-m :仅执行满足mark表达式的测试用例。only run tests matching given mark expression。For example: -m 'mark1 and not mark2'.

 

pytest之fixture

fixture:即测试用例执行的环境准备和清理,在unittest中提现为setUp/tearDown/setUpClass/tearDownClass

fixture主要的目的是为了提供一种手段去执行重复的、基本的内容。

例如:测试某个电商网站的功能,登录和退出就可以用到fixture,几乎每个用例都需要登录和退出。

 

定义fixture:在函数声明前加上标记  @pytest.fixture   在函数内部通过yield关键字分割环境准备和清理。

 

conftest.py文件专门用来写公用的fixture,不需要引用,直接用标记即可使用。(必须和test_*.py在一个层级,或位于它的父级)

conftest可以按路径写多个。使用时有就近原则。

 1 driver = None
 2 @pytest.fixture(scope='class')
 3 def login():
 4     #前置
 5     global driver
 6     driver = webdriver.Chrome()
 7     lg = ...
 8     yield (lg,driver)  #分割线 + 返回值
 9     #后置
10 
11 
12 @pytest.fixture(scope='function')  
13 # 默认就是函数级别。也可以简写成:@pytest.fixture
14 # scope:"function"(default), "class", "module", "package" or "session"
15 def reresh_page():
16     global driver
17     yield    #分割线
18     driver.refresh()
View Code

相关文章:

  • 2021-05-22
  • 2022-01-07
  • 2021-10-12
  • 2021-10-09
  • 2021-08-07
  • 2021-07-17
  • 2021-08-22
  • 2021-11-27
猜你喜欢
  • 2021-05-04
  • 2022-12-23
  • 2021-10-03
  • 2021-07-15
  • 2021-12-24
  • 2021-11-06
  • 2021-10-01
相关资源
相似解决方案