Pytest学习(一)- 入门及基础

 

一、安装pytest

pip install -U pytest

二、快速入门

示例代码如下:

# coding: utf-8 


def add(x):
    return x + 2;


class TestClass(object):
    # 测试是否相等
    def test_add(self):
        assert add(2) == 5

    # 测试包含
    def test_in(self):
        a = 'hello world'
        b = 'he'
        assert b in a

    # 测试不包含
    def test_not_in(self):
        a = 'Hello'
        b = 'hi'
        assert b not in a

1、执行

命令行当前文件同级目录下,输入如下命令:

pytest

说明:

  • 只执行 pytest ,会查找当前目录及其子目录下以  test_*.py  或 *_test.py 文件,找到文件后,在文件中找到以  test 开头函数并执行

  • 只想执行某个文件,可以 pytest test_demo.py

  • 加上-q,就是显示简单的结果:pytest -q test_demo.py

用Pytest写用例时候,一定要按照下面的规则去写,否则不符合规则的测试用例是不会执行的

三、Pytest用例的设计原则

  1. 文件名以 test_.py 文件和_test.py

  2. 以  test_ 开头的函数

  3. 以  Test 开头的类,不能包含 init 方法

  4. 以  test_ 开头的类里面的方法

  5. 所有的包 pakege 必需要有__init__.py 文件

四、Pytest执行用例规则

下面以windows系统为例,使用命令来来执行pytest

1、指定目录下的所有用例

pytest

2、执行某一个py文件下用例

pytest 文件名.py

3、运行test_demo.py文件中模块里面的某个函数,或者某个类,某个类里面的方法

说明:加v和不加-v都可以,加-v的话,打印的信息更详细

pytest -v test_demo.py::TestClass::test_add

pytest test_demo.py::TestClass::test_not_in

pytest test_demo.py::test_in

4、运行test_demo.py 模块里面,测试类里面的某个方法

pytest test_demo.py::test_in

5、-m 标记表达式(后面有详解)

pytest -m login

将运行用 @pytest.mark.login 装饰器修饰的所有测试,后面有详解!

 

五、使用Pycharm执行pytest

1、File->settings->python integrated tools->Testing下的default testrunner修改为Pytest

注意:

pytest兼容unittest脚本,所以不影响之前使用unittest编写的脚本

2、并不是修改完以上配置,就一定好用,如上面方法修改完仍不好用,参考下面方案:

  • 检查pycharm中的python interpreter是否设置为Python安装目录下的Python.exe

  • pycharm设置为国内源,如豆瓣、清华、阿里云等等!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值