Selenium3自动化测试【38】单元测试Pytest

pytest测试框架也是主流的一个测试框架,推荐使用该框架,对比unnitest框架来说,其效率更高

1.Pytest介绍

pytest测试框架也是主流的一个测试框架,推荐使用该框架,对比unnitest框架来说,其不需要像unittest那样单独创建类继承unittest.TestCase。它使用起来非常简单,只需要创建测试类或者测试文件,然后以test开头即可,pytest可以按照这个规则找到测试用例并执行。
pytest测试框架,主要有以下几个特点:

  • 简单灵活,容易上手,文档丰富;
  • 支持用简单的assert语句实现丰富的断言,无需复杂的self.assert*函数
  • 支持参数化;
  • 兼容unittest和 nose测试集
  • 能够支持简单的单元测试和复杂的功能测试,还可应用到接口自动化测试(pytest+requests)中;
  • 丰富的插件生态,具有很多第三方插件,并且可以自定义扩展,如pytest-Selenium(集成Selenium)等;
  • 支持重复执行失败的case等;
  • 方便和持续集成工具jenkins集成;
  • 可以很好的和jenkins集成。

2.安装Pytest

pytest不是Python默认的package,需要手动安装。其同时可以在windows、unix系统上安装。最新的pytest版本为5.4.1,pytest5.4.1支持Python 3.5、3.6、3.7版本。本书采取(书籍资料包中)的Python版本为Python3.7,因此可以与pytest结合使用。
打开windows系统的cmd命令窗口,在命令行中运行以下命令:
pip install -U pytest

注:
通过cmd安装pytest,可能下载过程较长或安装过程报错中断,多尝试几次。

安装进度,如图所示。

图 pytest安装

:::

如仍然安装不成功,可以指定国内镜像,如国内的清华大学开源软件镜像站,地址是:https://mirrors.tuna.tsinghua.edu.cn/,命令如下:
pip install --index https://mirrors.ustc.edu.cn/pypi/web/simple/ pytest
安装进度,如下所示。

C:\Windows\system32>pip install --index https://mirrors.ustc.edu.cn/pypi/web/simple/ pytest
Looking in indexes: https://mirrors.ustc.edu.cn/pypi/web/simple/
Collecting pytest
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/c7/e2/c19c667f42f72716a7d03e8dd4d6f63f47d39feadd44cc1ee7ca3089862c/pytest-5.4.1-py3-none-any.whl (246kB)
     |████████████████████████████████| 256kB 1.7MB/s
Collecting pluggy<1.0,>=0.12 (from pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/a0/28/85c7aa31b80d150b772fbe4a229487bc6644da9ccb7e427dd8cc60cb8a62/pluggy-0.13.1-py2.py3-none-any.whl
Collecting colorama; sys_platform == "win32" (from pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/c9/dc/45cdef1b4d119eb96316b3117e6d5708a08029992b2fee2c143c7a0a5cc5/colorama-0.4.3-py2.py3-none-any.whl
Collecting py>=1.5.0 (from pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/99/8d/21e1767c009211a62a8e3067280bfce76e89c9f876180308515942304d2d/py-1.8.1-py2.py3-none-any.whl (83kB)
     |████████████████████████████████| 92kB 2.0MB/s
Collecting more-itertools>=4.0.0 (from pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/72/96/4297306cc270eef1e3461da034a3bebe7c84eff052326b130824e98fc3fb/more_itertools-8.2.0-py3-none-any.whl (43kB)
     |████████████████████████████████| 51kB 3.4MB/s
Collecting packaging (from pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/62/0a/34641d2bf5c917c96db0ded85ae4da25b6cd922d6b794648d4e7e07c88e5/packaging-20.3-py2.py3-none-any.whl
Collecting attrs>=17.4.0 (from pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/a2/db/4313ab3be961f7a763066401fb77f7748373b6094076ae2bda2806988af6/attrs-19.3.0-py2.py3-none-any.whl
Collecting atomicwrites>=1.0; sys_platform == "win32" (from pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/52/90/6155aa926f43f2b2a22b01be7241be3bfd1ceaf7d0b3267213e8127d41f4/atomicwrites-1.3.0-py2.py3-none-any.whl
Collecting importlib-metadata>=0.12; Python_version < "3.8" (from pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/8b/03/a00d504808808912751e64ccf414be53c29cad620e3de2421135fcae3025/importlib_metadata-1.5.0-py2.py3-none-any.whl
Collecting wcwidth (from pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/58/b4/4850a0ccc6f567cc0ebe7060d20ffd4258b8210efadc259da62dc6ed9c65/wcwidth-0.1.8-py2.py3-none-any.whl
Collecting six (from packaging->pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/65/eb/1f97cb97bfc2390a276969c6fae16075da282f5058082d4cb10c6c5c1dba/six-1.14.0-py2.py3-none-any.whl
Collecting pyparsing>=2.0.2 (from packaging->pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/5d/bc/1e58593167fade7b544bfe9502a26dc860940a79ab306e651e7f13be68c2/pyparsing-2.4.6-py2.py3-none-any.whl (67kB)
     |████████████████████████████████| 71kB 4.8MB/s
Collecting zipp>=0.5 (from importlib-metadata>=0.12; Python_version < "3.8"->pytest)
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/b2/34/bfcb43cc0ba81f527bc4f40ef41ba2ff4080e047acb0586b56b3d017ace4/zipp-3.1.0-py3-none-any.whl
Installing collected packages: zipp, importlib-metadata, pluggy, colorama, py, more-itertools, six, pyparsing, packaging, attrs, atomicwrites, wcwidth, pytest
Successfully installed atomicwrites-1.3.0 attrs-19.3.0 colorama-0.4.3 importlib-metadata-1.5.0 more-itertools-8.2.0 packaging-20.3 pluggy-0.13.1 py-1.8.1 pyparsing-2.4.6 pytest-5.4.1 six-1.14.0 wcwidth-0.1.8 zipp-3.1.0
WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'Python -m pip install --upgrade pip' command.

检查您是否安装了正确的版本
pytest --version。

C:\Windows\system32>pytest --version
This is pytest version 5.4.1, imported from d:\program files\python37\lib\site-packages\pytest\__init__.py

Pytest帮助命令
pytest --help或pytest -h。

E:\pytestDemo>pytest --help
usage: pytest [options] [file_or_dir] [file_or_dir] [...]

positional arguments:
  file_or_dir

general:
  -k EXPRESSION         only run tests which match the given substring expression. An expression is a Python evaluatable
                        expression where all names are substring-matched against test names and their parent classes.
                        Example: -k 'test_method or test_other' matches all test functions and classes whose name
                        contains 'test_method' or 'test_other', while -k 'not test_method' matches those that don't
                        contain 'test_method' in their names. -k 'not test_method and not test_other' will eliminate the
                        matches. Additionally keywords are matched to classes and functions containing extra names in
                        their 'extra_keyword_matches' set, as well as functions which have names assigned directly to
                        them. The matching is case-insensitive.
  -m MARKEXPR           only run tests matching given mark expression. example: -m 'mark1 and not mark2'.
  --markers             show markers (builtin, plugin and per-project ones).
  -x, --exitfirst       exit instantly on first error or failed test.
  --maxfail=num         exit after first num failures or errors.

3.Pytest案例实战

3.1. pytest基础案例

通过PyCharm在工程目录下,创建pytestDemo的Python package,Pytest的案例均存放在pytestDemo下。
pytest测试用例编写非常简单,pytest可以在不同的函数、包中发现用例,但pytest有如下约束。

  • 文件名以test_(如:test_.py)开头或以_test(如: _test.py)结尾的py文件;
  • 以test_开头的函数或test_开头的方法;
  • 以Test开头的类,并且不能带有 init 方法;
  • 要注意的是所有的包必须要有init.py文件(在PyCharm中会自动生成)。

3.1.1 创建基础待测方法

在pytestDemo下新建test_demo.py文件,代码如下:

def add(a,b):
    return  a + b

def test_add():
    assert add(2,3) == 5

3.1.2 运行测试方法

通过cmd进入到test_demo.py所在的文件夹下,然后运行pytest,如下所示。

E:\>cd pytestDemo
E:\pytestDemo>pytest
================================================= test session starts =================================================
platform win32 -- Python 3.7.5, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: E:\pytestDemo
collected 1 item

test_demo.py .                                                                                                   [100%]
================================ 1 passed in 0.02s =============

将test_demo.py将代码进行变动,将实际值与期望值改成不一致,代码如下:

def add(a,b):
    return  a + b

def test_add():
    assert add(2,3) == 6

cmd进入到test_demo.py所在的文件夹下,然后运行pytest,如下所示。

E:\pytestDemo>pytest
======================= test session starts ===========================
platform win32 -- Python 3.7.5, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: E:\pytestDemo
collected 1 item
test_demo.py F                                                                                                   [100%]
======================= FAILURES =========================
_____________________ test_add __________________________
    def test_add():
>       assert add(2,3) == 6
E       assert 5 == 6
E        +  where 5 = add(2, 3)
test_demo.py:5: AssertionError
========================   short test summary info ==========================
FAILED test_demo.py::test_add - assert 5 == 6
==================== 1 failed in 0.06s ============================

3.2. 测试用例存放在类中

可将测试用例放在测试类中,通过执行测试类,而执行类中的测试用例。

3.2.1 优化测试代码

将test_demo.py将代码进行优化,代码如下:

def add(a, b):
    return a + b

  def minus(a, b):
    return a - b

class TestClass:
    def test_add(self):
        assert add(2, 3) == 5

    def test_minus(self):
        assert minus(3, 2) == 2

3.2.2 运行优化后的测试方法

cmd进入到test_demo.py所在的文件夹下,然后运行pytest,结果如下所示。

E:\pytestDemo>pytest
===================== test session starts ==========================
platform win32 -- Python 3.7.5, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: E:\pytestDemo
collected 2 items
test_demo.py .F                                                                                                  [100%]
=================== FAILURES =========================
___________________ TestClass.test_minus _______________________________
self = <pytestDemo.test_demo.TestClass object at 0x0000023E3C369FC8>
    def test_minus(self):
>       assert minus(3, 2) == 2
E       assert 1 == 2
E        +  where 1 = minus(3, 2)

test_demo.py:27: AssertionError
===================== short test summary info ===========
FAILED test_demo.py::TestClass::test_minus - assert 1 == 2
=============== 1 failed, 1 passed in 0.06s ==============================

【测试测试课程】8折销售中【6月18日--6月24日】....

《全栈测试系列视频》课程






图书京东、当当有售

京东:https://item.jd.com/12784287.html
当当:http://product.dangdang.com/29177828.html)!

posted @ 2022-06-19 21:34  BlaLeo  阅读(319)  评论(0编辑  收藏  举报