pytest框架学习_1

pytest框架

安装pytest

pip install -U pytest

查看安装版本

  • pip show pytest
  • pytest --version

先看官网的一个例子,这个例子告诉你pytest的执行规则:

  • 新建一个test_sample.py文件,代码如下:
def func(x):
    return x + 1

def test_anwder():
    assert func(3) == 4
pytest执行信息:
E:\PycharmProjects\pytest_study
λ pytest     # 文件名必须以test_开头,否则执行pytest会找不到用例
============================== test session starts =============================== platform win32 -- Python 3.7.3, pytest-4.5.0, py-1.8.0, pluggy-0.11.0
rootdir: E:\PycharmProjects\pytest_study
collected 1 item

first_pytest_demo.py .                                                     [100%]

============================ 1 passed in 0.12 seconds ============================

Note:

  • ’λ‘ 是cmder工具的符号相当于cmd的 ‘>’,不明白可忽略。
  • pytest运行规则:查找当前目录及其子目录下以test_.py或_test.py文件,找到文件后,在文件中找到以test开头函数并执行

多个用例可以放在一个class里

# content of test_class.py
class TestClass(object):
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

pytest执行信息
E:\PycharmProjects\pytest_study
λ pytest
============================== test session starts =============================== platform win32 -- Python 3.7.3, pytest-4.5.0, py-1.8.0, pluggy-0.11.0
rootdir: E:\PycharmProjects\pytest_study
collected 2 items

test_pytest_demo.py .F                                                      [100%]

==================================== FAILURES ==================================== _______________________________ TestClass.test_two _______________________________

self = <test_pytest_demo.TestClass object at 0x00000000036E3CC0>

def test_two(self):
x = "hello"

> assert hasattr(x, 'check')
> E       AssertionError: assert False
> E        +  where False = hasattr('hello', 'check')

test_pytest_demo.py:25: AssertionError
======================= 1 failed, 1 passed in 0.16 seconds =======================

是不是看着很眼熟?没错,和python的unittest很相似。

pytest四种report:

1.直接pytest,会找到当前目录下所有test_xxx.py或者xxx_test.py格式的文件,然后找到文件中的以Test开头的类中以test开头的测试函数,并执行。

2.pytest test_sample.py,指定一个测试文件执行。

3.pytest -q test_sample.py,报告减少冗余的信息。

4.pytest -v test_sample.py,报告增加冗余的信息,与unittest.TextTestRunner(verbosity=2)相同,都是打印更多详细的执行信息。

pytest -h或者pytest --help 可以查看pytest的用法

这里就不贴了,自己执行看一下

cmd下执行pytest的三种方式

1.pytest (推荐)

2.py.test

3.python -m pytest

posted @   我是一言  阅读(347)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示