pytest框架快速入门一

时间好快啊,转眼间2021年了hhhhh,虽然是元旦假期但学习的心一点都不能松懈啊,今天向大家先简单的介绍一下pytest框架的一些特性,其实呢就博主个人认为作为一名自动化测试工程师pytest框架与unittest框架两种都是必须要会的。前面的博主向大家介绍过unittest框架后面将会抽出一点时间讲解一下pytest框架使用的一些方法。

安装:pip install -U pytest

查看安装版本:pytest --version

哈哈哈,首先呢先介绍一下pytest框架的setup 与 teardown,其分为模块级、类级、功能级、函数集。其实我们平时最常用的函数集与类级,其余的我们平时用的很少,博主除了函数集与类集其余的基本没有用过。

模块级 (setup_module/
teardown_module) 不在类中的函数有用
函数级 (setup/
teardown) 不在类中的函数有用
类级 (setup_class/
teardown_class)只在 类中前后运行一次。
方法级 (setup_method/
teardown_methond) 运行在类中方法始末

下面博主会分别举一下函数集与类级的例子。

函数集:每执行一条用例前后执行setup与teardown

import pytest


class Test_ABC:

    def setup(self):
      print("------->setup_method")

    def teardown(self):
      print("------->teardown_method")

    def test_a(self):
      print("------->test_a")
      assert 1

    def test_b(self):
      print("------->test_b")


if __name__ == '__main__':
    pytest.main(['-s',"test_abc.py"])

其中-s参数表示执行结果会打印出测试用例中print中的输出语句

查看输入

类集:当前测试类下的所有用例执行前运行一次结束后执行一次

import pytest


class Test_ABC:

    def setup_class(self):
      print("------->setup_method")

    def teardown_class(self):
      print("------->teardown_method")

    def test_a(self):
      print("------->test_a")
      assert 1

    def test_b(self):
      print("------->test_b")


if __name__ == '__main__':
    pytest.main(['-s',"test_abc.py"])

查看执行结果:

setup与teardown中的各个方法在面对不同的场景大家灵活即可,很简单的我相信绝大多数的小伙伴都已掌握了。

pytest框架中assert断言使用

断言支持最常见的子表达式,包含调用属性,包含三元和一元运算符,现在博主举几个常用的例子吧

assert "h" in “hello"  判断h在hello中

assert 3==4(判断3==4)

assert 3!=4(判断3!=4)

assert f()==4(判断f()方法的返回值是否=4)

assert5>4(判断5>4是否为真)

assert not xx (判断xx不为真)

大致比较实用的方法就是这些了。

后面关于pytest框架的知识会持续更新的,今天就先先到这里吧,该睡了,时间过的好快啊,哈哈哈

 

Guess you like

Origin blog.csdn.net/HUJIANLAILE/article/details/112069025