pytest是一个能够简化测试系统构建、方便测试规模扩展的框架,它让测试变得更具表现力和可读性--模版代码不再是必需的。

只需要几分钟的时间,就可以对你的应用开始一个简单的单元测试或者复杂的功能测试。

1. 安装

  • 命令行执行如下命令:pipenv install pytest==5.1.3

  • 查看安装的版本信息:pipenv run pytest --version

2. 创建你的第一个测试用例

它只有四行代码:

# src/chapter-1/test_sample.py

def func(x):
return x + 1 def test_sample():
assert func(3) == 5

通过以下命令执行测试:

λ pipenv run pytest src/chapter-1/test_sample.py
============================= test session starts ==============================
platform win32 -- Python 3.7.3, pytest-5.1.3, py-1.8.0, pluggy-0.13.0
rootdir: D:\Personal Files\Projects\pytest-chinese-doc
collected 1 item src\chapter-1\test_sample.py F [100%] =================================== FAILURES ===================================
_________________________________ test_sample __________________________________ def test_sample():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3) src\chapter-1\test_sample.py:28: AssertionError
============================== 1 failed in 0.05s ===============================

pytest返回一个失败的测试报告,因为func(3)不等于5

3. 执行多个测试用例

执行pipenv run pytest命令,它会执行当前及其子文件夹中,所有命名符合test_*.py或者*_test.py规则的文件;

4. 触发一个指定异常的断言

使用raises可以检查代码是否抛出一个指定的异常:

# src/chapter-1/test_sysexit.py

import pytest

def f():
# 解释器请求退出
raise SystemExit(1) def test_mytest():
with pytest.raises(SystemExit):
f()

执行这个测试用例时,加上-q选项可以查看精简版的测试报告:

λ pipenv run pytest -q src/chapter-1/test_sysexit.py
. [100%]
1 passed in 0.01s

5. 在一个类中组织多个测试用例

pytest可以让你很容易的通过创建一个测试类来包含多个测试用例:

# src/chapter-1/test_class.py

class TestClass:
def test_one(self):
x = 'this'
assert 'h' in x def test_two(self):
x = 'hello'
assert hasattr(x, 'check')

现在我们来执行这个测试用例:

λ pipenv run pytest -q src/chapter-1/test_class.py
.F [100%]
=================================== FAILURES ===================================
______________________________ TestClass.test_two ______________________________ self = <test_class.TestClass object at 0x000001D364778E48> def test_two(self):
x = 'hello'
> assert hasattr(x, 'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check') src\chapter-1\test_class.py:30: AssertionError
1 failed, 1 passed in 0.05s

从输出的报告中我们可以看到:

  • test_one测试通过,用.表示;test_two测试失败,用F表示;
  • 清除的看到,test_two失败的原因是:False = hasattr('hello', 'check')

注意:

测试类要符合特定的规则,pytest才能发现它:

  • 测试类的命令要符合Test*规则;
  • 测试类中不能有__init__()方法;

6. 申请一个唯一的临时目录

pytest提供一些内置的fixtures,可以用来请求一些系统的资源。例如,一个唯一的临时性目录:

# src/chapter-1/test_tmpdir.py

def test_needsfiles(tmpdir):
print(tmpdir)
assert 0

在测试用例中,以形参的方式使用内置的tempdir fixturepytest会事先创建一个目录,并将一个py.path.local对象作为实参传入;

现在,我们来执行这个测试用例:

λ pipenv run pytest -q src/chapter-1/test_tmpdir.py
F [100%]
=================================== FAILURES ===================================
_______________________________ test_needsfiles ________________________________ tmpdir = local('C:\\Users\\luyao\\AppData\\Local\\Temp\\pytest-of-luyao\\pytest-1\\test_needsfiles0') def test_needsfiles(tmpdir):
print(tmpdir)
> assert 0
E assert 0 src\chapter-1\test_tmpdir.py:25: AssertionError
----------------------------- Captured stdout call ----------------------------- C:\Users\luyao\AppData\Local\Temp\pytest-of-luyao\pytest-1\test_needsfiles0
1 failed in 0.05s

可以使用如下命令查看所有可用的fixtures,如果想同时查看以_开头的fixtures,需要添加-v选项:

λ pipenv run pytest -q -v --fixtures
============================= test session starts ==============================
platform win32 -- Python 3.7.3, pytest-5.1.3, py-1.8.0, pluggy-0.13.0
rootdir: D:\Personal Files\Projects\pytest-chinese-doc
collected 5 items
cache
Return a cache object that can persist state between testing sessions. cache.get(key, default)
cache.set(key, value) Keys must be a ``/`` separated value, where the first part is usually the
name of your plugin or application to avoid clashes with other cache users. Values can be any object handled by the json stdlib module. capsys
Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``. The captured output is made available via ``capsys.readouterr()`` method
calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``text`` objects. capsysbinary
Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``. The captured output is made available via ``capsysbinary.readouterr()``
method calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``bytes`` objects. capfd
Enable text capturing of writes to file descriptors ``1`` and ``2``. The captured output is made available via ``capfd.readouterr()`` method
calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``text`` objects. capfdbinary
Enable bytes capturing of writes to file descriptors ``1`` and ``2``. The captured output is made available via ``capfd.readouterr()`` method
calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``byte`` objects. doctest_namespace [session scope]
Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests. pytestconfig [session scope]
Session-scoped fixture that returns the :class:`_pytest.config.Config` object. Example:: def test_foo(pytestconfig):
if pytestconfig.getoption("verbose") > 0:
... record_property
Add an extra properties the calling test.
User properties become part of the test report and are available to the
configured reporters, like JUnit XML.
The fixture is callable with ``(name, value)``, with value being automatically
xml-encoded. Example:: def test_function(record_property):
record_property("example_key", 1) record_xml_attribute
Add extra xml attributes to the tag for the calling test.
The fixture is callable with ``(name, value)``, with value being
automatically xml-encoded record_testsuite_property [session scope]
Records a new ``<property>`` tag as child of the root ``<testsuite>``. This is suitable to
writing global information regarding the entire test suite, and is compatible with ``xunit2`` JUnit family. This is a ``session``-scoped fixture which is called with ``(name, value)``. Example: .. code-block:: python def test_foo(record_testsuite_property):
record_testsuite_property("ARCH", "PPC")
record_testsuite_property("STORAGE_TYPE", "CEPH") ``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped. caplog
Access and control log capturing. Captured logs are available through the following properties/methods:: * caplog.text -> string containing formatted log output
* caplog.records -> list of logging.LogRecord instances
* caplog.record_tuples -> list of (logger_name, level, message) tuples
* caplog.clear() -> clear captured records and formatted log output string monkeypatch
The returned ``monkeypatch`` fixture provides these
helper methods to modify objects, dictionaries or os.environ:: monkeypatch.setattr(obj, name, value, raising=True)
monkeypatch.delattr(obj, name, raising=True)
monkeypatch.setitem(mapping, name, value)
monkeypatch.delitem(obj, name, raising=True)
monkeypatch.setenv(name, value, prepend=False)
monkeypatch.delenv(name, raising=True)
monkeypatch.syspath_prepend(path)
monkeypatch.chdir(path) All modifications will be undone after the requesting
test function or fixture has finished. The ``raising``
parameter determines if a KeyError or AttributeError
will be raised if the set/deletion operation has no target. recwarn
Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions. See http://docs.python.org/library/warnings.html for information
on warning categories. tmpdir_factory [session scope]
Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session. tmp_path_factory [session scope]
Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session. tmpdir
Return a temporary directory path object
which is unique to each test function invocation,
created as a sub directory of the base temporary
directory. The returned object is a `py.path.local`_
path object. .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html tmp_path
Return a temporary directory path object
which is unique to each test function invocation,
created as a sub directory of the base temporary
directory. The returned object is a :class:`pathlib.Path`
object. .. note:: in python < 3.6 this is a pathlib2.Path ============================ no tests ran in 0.10s =============================

GitHub仓库地址:https://github.com/luizyao/pytest-chinese-doc

1、pytest中文文档--安装和入门的更多相关文章

  1. IdentityServer4 中文文档 -16- (快速入门)使用 EntityFramework Core 存储配置数据

    IdentityServer4 中文文档 -16- (快速入门)使用 EntityFramework Core 存储配置数据 原文:http://docs.identityserver.io/en/r ...

  2. IdentityServer4 中文文档 -15- (快速入门)添加 JavaScript 客户端

    IdentityServer4 中文文档 -15- (快速入门)添加 JavaScript 客户端 原文:http://docs.identityserver.io/en/release/quicks ...

  3. IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity

    IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity 原文:http://docs.identityserver.io/en/release ...

  4. IdentityServer4 中文文档 -13- (快速入门)切换到混合流并添加 API 访问

    IdentityServer4 中文文档 -13- (快速入门)切换到混合流并添加 API 访问 原文:http://docs.identityserver.io/en/release/quickst ...

  5. IdentityServer4 中文文档 -12- (快速入门)添加外部认证支持

    IdentityServer4 中文文档 -12- (快速入门)添加外部认证支持 原文:http://docs.identityserver.io/en/release/quickstarts/4_e ...

  6. IdentityServer4 中文文档 -11- (快速入门)添加基于 OpenID Connect 的用户认证

    IdentityServer4 中文文档 -11- (快速入门)添加基于 OpenID Connect 的用户认证 原文:http://docs.identityserver.io/en/releas ...

  7. IdentityServer4 中文文档 -8- (快速入门)设置和概览

    IdentityServer4 中文文档 -8- (快速入门)设置和概览 原文:http://docs.identityserver.io/en/release/quickstarts/0_overv ...

  8. IdentityServer4 中文文档 -9- (快速入门)使用客户端凭证保护API

    IdentityServer4 中文文档 -9- (快速入门)使用客户端凭证保护API 原文:http://docs.identityserver.io/en/release/quickstarts/ ...

  9. IdentityServer4 中文文档 -10- (快速入门)使用密码保护API

    IdentityServer4 中文文档 -10- (快速入门)使用密码保护API 原文:http://docs.identityserver.io/en/release/quickstarts/2_ ...

随机推荐

  1. 比特平面分层(一些基本的灰度变换函数)基本原理及Python实现

    1. 基本原理 在灰度图中,像素值的范围为[0, 255],即共有256级灰度.在计算机中,我们使用8比特数来表示每一个像素值.因此可以提取出不同比特层面的灰度图.比特层面分层可用于图片压缩:只储存较 ...

  2. zookeeper 集群配置

    安装前要先确保配置好 jdk,这里不在讲述 一. 将zookeeper 安装包下载到你想要的目录 下载地址:http://mirrors.hust.edu.cn/apache/zookeeper/ m ...

  3. Java——集合类

    1.容器的打印 import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import jav ...

  4. 【0729 | Day 3】Python基础(一)

    Part 1 变量 一.什么是变量? 字面意思:变化的量. 而在计算机中,我们可以将它理解为世间万物变化的状态. 二.为什么要有变量? 首先,无论是我们还是计算机都需要变量来记录发生的状态的变化,其次 ...

  5. Oracle 12cR1 RAC集群安装(一)--环境准备

    基本环境 操作系统版本 RedHat6.7 数据库版本 12.1.0.2 数据库名称 testdb 数据库实例 testdb1.testdb2 (一)安装服务器硬件要求 配置项目 参数要求 网卡 每台 ...

  6. 用 程序 解决 windows防火墙 的 弹窗 问题

    今天用户反馈了一个问题,运行程序弹了个框 这个只有程序第一次运行会出来,之后就不会了. 当然改个程序名字,又会弹出来. 强烈怀疑是写到了注册表,果然被我找到了. “HKEY_LOCAL_MACHINE ...

  7. Python入门基础(10)_异常_1

    最近有点忙,到现在快一个月没写了,罪过罪过,继续学习 异常:python程序在运行时,如果python解释器遇到一个错误,那么程序就会停止执行,并且会提示一些错误信息,这就是异常. 抛出异常:程序停止 ...

  8. (二十一)c#Winform自定义控件-气泡提示

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...

  9. lnmp环境搭建方法

    网上目前的一键搭建方法: 命令行安装: 1.源码编译安装:(个性化配置,安装配置过程繁琐) 2.使用yum或apt直接安装:(使用编译好的二进制文件安装,速度快) 3.军哥的lnmp一键脚本安装: 4 ...

  10. Java虚拟机详解(五)------JVM参数(持续更新)

    JVM参数有很多,其实我们直接使用默认的JVM参数,不去修改都可以满足大多数情况.但是如果你想在有限的硬件资源下,部署的系统达到最大的运行效率,那么进行相关的JVM参数设置是必不可少的.下面我们就来对 ...