51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 779|回复: 0
打印 上一主题 下一主题

[转贴] 测试新人如何掌握好Pytest!

[复制链接]
  • TA的每日心情
    擦汗
    7 小时前
  • 签到天数: 942 天

    连续签到: 1 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2022-8-9 09:58:07 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
     Pytest简介
      Pytest is a mature full-featured Python testing tool that helps you write better programs.The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries.
      通过官方网站介绍我们可以了解到,pytest是一个非常成熟的全功能的python测试框架,主要有以下几个特点:
      简单灵活易上手
      支持参数化
      支持简单的单元测试和复杂的[url=]功能测试[/url],还可以用来做自动化测试
      具有很多第三方插件,并且可以自定义扩展
      测试用例的skip和xfail处理
      可以很好的和Jenkins集成
      支持运行由nose, unittest编写的测试用例
      Pytest安装
      1.直接使用pip命令安装
    1. pip install -U pytest    # -U是如果已安装会自动升级最新版本
    复制代码
    2.验证安装结果

    1. pytest --version    # 展示当前安装版本

    2. C:\Users\edison>pytest --version
    3. pytest 6.2.5
    复制代码
    3.在pytest测试框架中,要遵循以下约束:
      测试文件名要符合test_*.py或*_test.py格式(例如test_min.py)
      测试类要以Test开头,且不能带有init方法
      在单个测试类中,可以包含一个或多个test_开头的函数
      Pytest测试执行
      pytest进行测试比较简单,我们来看一个实例:
    1. import pytest    # 导入pytest包

    2. def test_001():    # 函数以test_开头
    3.     print("test_01")

    4. def test_002():
    5.     print("test_02")

    6. if __name__ == '__main__':
    7.     pytest.main(["-v","test_1214.py"])    # 调用pytest的main函数执行测试
    复制代码
    这里我们定义了了两个测试函数,直接打印出结果,下面执行测试:
    1. ============================= test session starts =============================
    2. platform win32 -- Python 3.8.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- D:\Code\venv\Scripts\python.exe
    3. cachedir: .pytest_cache
    4. rootdir: D:\Code
    5. collecting ... collected 2 items

    6. test_1214.py::test_001 PASSED                                            [ 50%]
    7. test_1214.py::test_002 PASSED                                            [100%]

    8. ============================== 2 passed in 0.11s ==============================

    9. Process finished with exit code 0
    复制代码
    输出结果中显示执行了多少条案例、对应的测试模块、通过条数以及执行耗时。
      测试类主函数
    pytest.main(["-v","test_1214.py"])

     通过python代码执行 pytest.main()
      1.直接执行pytest.main() 【自动查找当前目录下,以test_开头的文件或者以_test结尾的py文件】
      2.设置pytest的执行参数 pytest.main(['--html=./report.html','test_login.py'])【执行test_login.py文件,并生成html格式的报告】
      main()括号内可传入执行参数和插件参数,通过[]进行分割,[]内的多个参数通过‘逗号,’进行分割
      运行目录及子包下的所有用例  pytest.main(['目录名'])
      运行指定模块所有用例  pytest.main(['test_reg.py'])
      运行指定模块指定类指定用例  pytest.main(['test_reg.py::TestClass::test_method'])  冒号分割
      -m=xxx: 运行打标签的用例
      -reruns=xxx:失败重新运行
      -q: 安静模式, 不输出环境信息
      -v: 丰富信息模式, 输出更详细的用例执行信息
      -s: 显示程序中的print/logging输出
      --resultlog=./log.txt 生成log
      --junitxml=./log.xml 生成xml报告
      断言方法
      pytest断言主要使用Python原生断言方法,主要有以下几种:
      == 内容和类型必须同时满足相等
      in 实际结果包含预期结果
      is 断言前后两个值相等
    1. import pytest    # 导入pytest包

    2. def add(x,y):    # 定义以test_开头函数
    3.     return x + y

    4. def test_add():
    5.     assert add(1,2) == 3    # 断言成功

    6. str1 = "Python,Java,Ruby"
    7. def test_in():
    8.     assert "PHP" in str1    # 断言失败

    9. if __name__ == '__main__':
    10.     pytest.main(["-v","test_pytest.py"])    # 调用main函数执行测试
    复制代码
    1. ============================= test session starts =============================
    2. platform win32 -- Python 3.8.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- D:\Code\venv\Scripts\python.exe
    3. cachedir: .pytest_cache
    4. rootdir: D:\Code
    5. collecting ... collected 2 items

    6. test_pytest.py::test_add PASSED                                          [ 50%]
    7. test_pytest.py::test_in FAILED                                           [100%]

    8. ================================== FAILURES ===================================
    9. ___________________________________ test_in ___________________________________

    10.     def test_in():
    11. >       assert "PHP" in str1
    12. E       AssertionError: assert 'PHP' in 'Python,Java,Ruby'

    13. test_pytest.py:11: AssertionError
    14. =========================== short test summary info ===========================
    15. FAILED test_pytest.py::test_in - AssertionError: assert 'PHP' in 'Python,Java...
    16. ========================= 1 failed, 1 passed in 0.18s =========================

    17. Process finished with exit code 0
    复制代码
     可以看到运行结果中明确指出了错误原因是“AssertionError”,因为PHP不在str1中。
      常用命令详解
      1.运行指定案例
    1. if __name__ == '__main__':
    2.     pytest.main(["-v","-s","test_1214.py"])
    复制代码
    2.运行当前文件夹包括子文件夹所有用例
    1. if __name__ == '__main__':
    2.     pytest.main(["-v","-s","./"])
    复制代码
    3.运行指定文件夹(code目录下所有用例)
    1. if __name__ == '__main__':
    2.     pytest.main(["-v","-s","code/"])
    复制代码
     4.运行模块中指定用例(运行模块中test_add用例)
    1. if __name__ == '__main__':
    2.     pytest.main(["-v","-s","test_pytest.py::test_add"])
    复制代码
    5.执行失败的最大次数
      使用表达式"--maxfail=num"来实现(注意:表达式中间不能存在空格),表示用例失败总数等于num 时停止运行。


    6.错误信息在一行展示
      在实际项目中如果有很多用例执行失败,查看报错信息将会很麻烦。使用"--tb=line"命令,可以很好解决这个问题。

    接口调用
    # -*- coding: utf-8 -*-
    import pytest
    import requests

    def test_agent():
        r = requests.post(
            url="http://127.0.0.1:9000/get_user",
            data={
                "name": "吴磊",
                "sex": 1
            },
            headers={"Content-Type": "application/json"}
        )
        print(r.text)
        assert r.json()['data']['retCode'] == "00" and r.json()['data']['retMsg'] == "调用成功"

    if __name__ == "__main__":
        pytest.main(["-v","test_api.py"])

    本地写一个查询用户信息的接口,通过pytest来调用,并进行接口断言。







    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

    x
    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-5-6 16:09 , Processed in 0.073619 second(s), 24 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表