安装pytest

1、在命令行中运行以下命令:

pip install -U pytest

2、检查已经安装的版本:

pytest --version
This is pytest version 3.7.2, imported from c:\python27\lib\site-packages\pytest.pyc

创建第一个测试用例

使用四行代码创建一个简单的测试函数:

# content of test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5

执行测试用例:

D:\test\Demo\Demo\Pytest>py.test -q test_sample.py
F [100%]
================================== FAILURES ===================================
_________________________________ test_answer _________________________________ def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3) test_sample.py:7: AssertionError
1 failed in 0.04 seconds

结果返回了一个失败的报告,因为func(3)不返回5。

注意:可以使用assert语句来验证测试的期望结果。 pytest的断言会自动断言出表达式的结果值,避免使用许多JUnit的方法。

运行多个测试
pytest会在当前目录及其子目录下运行test _ * .py或* _test.py形式的所有文件。 断言会抛出异常,使用raises可以查看某些代码引发的异常:

# content of test_sysexit.py
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()

使用“quiet”报告模式执行测试功能:

D:\test\Demo\Demo\Pytest>py.test -q test_sysexit.py
. [100%]
1 passed in 0.89 seconds

一个类中存在多个测试用例
一旦设计了多个测试用例,且你希望将它们分组到一个类中。 pytest使创建类,使类中包含多个测试用例:

import pytest

# content of 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')

pytest会运作python规则下的所有test,它发现有两个test_前缀的用例,所以我们通过传文件名来运行类中所有的测试用例。

D:\test\Demo\Demo\Pytest>py.test -q test_class.py
.F [100%]
================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________ self = <Pytest.test_class.TestClass instance at 0x00000000039BC448> def test_two(self):
x = "hello"
> assert hasattr(x, 'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check') test_class.py:10: AssertionError
1 failed, 1 passed in 0.05 seconds

第一次测试通过,第二次测试失败。 可以在断言中轻松查看到结果值,来判断失败的原因,来定位问题

请求唯一临时目录的测试用例
pytest提供了Builtin fixture / function参数来请求任意资源,比如一个唯一的临时目录:

# content of test_tmpdir.py
def test_needsfiles(tmpdir):
print (tmpdir)
assert 0

pytest将查找并调用fixture工厂来创建执行测试函数调用之前的资源,在测试运行之前,pytest会为每次测试运行调用创建一个独特的临时目录

D:\test\Demo\Demo\Pytest>py.test -q test_tmpdir.py
F [100%]
================================== FAILURES ===================================
_______________________________ test_needsfiles _______________________________ tmpdir = local('c:\\users\\admini~1\\appdata\\local\\temp\\pytest-of-Administrator\\pytest-2\\test_needsfiles0') def test_needsfiles(tmpdir):
print (tmpdir)
> assert 0
E assert 0 test_tmpdir.py:4: AssertionError
---------------------------- Captured stdout call -----------------------------
c:\users\admini~1\appdata\local\temp\pytest-of-Administrator\pytest-2\test_needsfiles0
1 failed in 0.05 seconds D:\test\Demo\Demo\Pytest>py.test -q test_tmpdir.py
F [100%]
================================== FAILURES ===================================
_______________________________ test_needsfiles _______________________________ tmpdir = local('c:\\users\\admini~1\\appdata\\local\\temp\\pytest-of-Administrator\\pytest-3\\test_needsfiles0') def test_needsfiles(tmpdir):
print (tmpdir)
> assert 0
E assert 0 test_tmpdir.py:4: AssertionError
---------------------------- Captured stdout call -----------------------------
c:\users\admini~1\appdata\local\temp\pytest-of-Administrator\pytest-3\test_needsfiles0
1 failed in 0.05 seconds

显示内置和自定义的fixtures

pytest --fixtures # shows builtin and custom fixtures

内置和自定义的fixtures如下:

D:\test\Demo\Demo\Pytest>pytest --fixtures
============================= test session starts =============================
platform win32 -- Python 2.7.12, pytest-3.7.2, py-1.5.4, pluggy-0.7.1
rootdir: D:\test\Demo\Demo\Pytest, inifile:
collected 13 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 capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
captured output available via ``capsys.readouterr()`` method calls
which return a ``(out, err)`` namedtuple. ``out`` and ``err`` will be ``text``
objects.
capsysbinary
Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
captured output available via ``capsys.readouterr()`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``bytes``
objects.
capfd
Enable capturing of writes to file descriptors ``1`` and ``2`` and make
captured output available via ``capfd.readouterr()`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``text``
objects.
capfdbinary
Enable capturing of write to file descriptors 1 and 2 and make
captured output available via ``capfdbinary.readouterr`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be
``bytes`` objects.
doctest_namespace
Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
pytestconfig
Session-scoped fixture that returns the :class:`_pytest.config.Config` object. Example:: def test_foo(pytestconfig):
if pytestconfig.getoption("verbose"):
...
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_property
(Deprecated) use record_property.
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
caplog
Access and control log capturing. Captured logs are available through the following 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
Return a TempdirFactory 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 ======================== no tests ran in 0.08 seconds =========================

请注意,除非添加-v选项,否则此命令将省略带有前导_的fixtures

D:\test\Demo\Demo\Pytest>pytest -v --fixtures
============================= test session starts =============================
platform win32 -- Python 2.7.12, pytest-3.7.2, py-1.5.4, pluggy-0.7.1 -- c:\python27\python.exe
cachedir: .pytest_cache
rootdir: D:\test\Demo\Demo\Pytest, inifile:
collected 13 items
cache -- c:\python27\lib\site-packages\_pytest\cacheprovider.py:298
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 -- c:\python27\lib\site-packages\_pytest\capture.py:205
Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
captured output available via ``capsys.readouterr()`` method calls
which return a ``(out, err)`` namedtuple. ``out`` and ``err`` will be ``text``
objects.
capsysbinary -- c:\python27\lib\site-packages\_pytest\capture.py:217
Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
captured output available via ``capsys.readouterr()`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``bytes``
objects.
capfd -- c:\python27\lib\site-packages\_pytest\capture.py:233
Enable capturing of writes to file descriptors ``1`` and ``2`` and make
captured output available via ``capfd.readouterr()`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``text``
objects.
capfdbinary -- c:\python27\lib\site-packages\_pytest\capture.py:249
Enable capturing of write to file descriptors 1 and 2 and make
captured output available via ``capfdbinary.readouterr`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be
``bytes`` objects.
doctest_namespace -- c:\python27\lib\site-packages\_pytest\doctest.py:507
Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
pytestconfig -- c:\python27\lib\site-packages\_pytest\fixtures.py:1079
Session-scoped fixture that returns the :class:`_pytest.config.Config` object. Example:: def test_foo(pytestconfig):
if pytestconfig.getoption("verbose"):
...
record_property -- c:\python27\lib\site-packages\_pytest\junitxml.py:241
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_property -- c:\python27\lib\site-packages\_pytest\junitxml.py:261
(Deprecated) use record_property.
record_xml_attribute -- c:\python27\lib\site-packages\_pytest\junitxml.py:272
Add extra xml attributes to the tag for the calling test.
The fixture is callable with ``(name, value)``, with value being
automatically xml-encoded
caplog -- c:\python27\lib\site-packages\_pytest\logging.py:328
Access and control log capturing. Captured logs are available through the following 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 -- c:\python27\lib\site-packages\_pytest\monkeypatch.py:16
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 -- c:\python27\lib\site-packages\_pytest\recwarn.py:18
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 -- c:\python27\lib\site-packages\_pytest\tmpdir.py:109
Return a TempdirFactory instance for the test session.
tmpdir -- c:\python27\lib\site-packages\_pytest\tmpdir.py:116
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 ======================== no tests ran in 0.09 seconds =========================

pytest 安装和入门的更多相关文章

  1. pytest_01_安装和入门

    目录 pytest 安装与入门 1.pip install -U pytest 2.创建一个test01.py的文件 3.在该目录下执行pytest(venv) 4.执行多个,新建一个py文件 tes ...

  2. pytest学习--快速入门

    一.pytest简介 Pytest是python的一种单元测试框架. pytest的特点: 入门简单,文档丰富 支持单元测试,功能测试 支持参数化,重复执行,部分执行,测试跳过 兼容其他测试框架(no ...

  3. Apache Hadoop2.x 边安装边入门

    完整PDF版本:<Apache Hadoop2.x边安装边入门> 目录 第一部分:Linux环境安装 第一步.配置Vmware NAT网络 一. Vmware网络模式介绍 二. NAT模式 ...

  4. bower安装使用入门详情

    bower安装使用入门详情   bower自定义安装:安装bower需要先安装node,npm,git全局安装bower,命令:npm install -g bower进入项目目录下,新建文件1.tx ...

  5. [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍

    前面介绍了很多Selenium基于自动测试的Python爬虫程序,主要利用它的xpath语句,通过分析网页DOM树结构进行爬取内容,同时可以结合Phantomjs模拟浏览器进行鼠标或键盘操作.但是,更 ...

  6. 虚拟光驱 DAEMON Tools Lite ——安装与入门

    DAEMON Tools Lite 是什么?它不仅仅是虚拟光驱.是的,你可以使用它制作.加载光盘映像,但是 DAEMON Tools 产品那么多,Lite版与其他版本究竟有什么不同呢?或者说,是什么让 ...

  7. Python 3.6.3 官网 下载 安装 测试 入门教程 (windows)

    1. 官网下载 Python 3.6.3 访问 Python 官网 https://www.python.org/ 点击 Downloads => Python 3.6.3 下载 Python ...

  8. 八:Lombok 安装、入门 - 消除冗长的 java 代码

    Lombok 安装.入门 - 消除冗长的 java 代码 前言:    逛开源社区的时候无意发现的,用了一段时间,觉得还可以,特此推荐一下.    lombok 提供了简单的注解的形式来帮助我们简化消 ...

  9. robotframework安装及入门指南

    将很久之前自己在本地记录的一些笔记发表到随笔来,希望能够帮到一些童鞋~ robotframework安装及入门指南 本文主要介绍robotframework在windows环境的安装过程! 安装步骤 ...

随机推荐

  1. sql service添加索引

    语法:CREATE [索引类型] INDEX 索引名称ON 表名(列名)WITH FILLFACTOR = 填充因子值0~100GO /*实例*/USE 库名GOIF EXISTS (SELECT * ...

  2. C#引用CefSharp并屏蔽鼠标右键和禁止拖动放置事件

    原文:C#引用CefSharp并屏蔽鼠标右键和禁止拖动放置事件 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/u013564470/article/ ...

  3. 第一个spring boot工程

    参考. 1. 碰到的问题: -出现bind:address already in use是因为当前项目正在运行,停掉当前项目即可.cmd中命令 netstat -nao 查看所有占用的端口及PID号, ...

  4. WPF实用指南一:在WPF窗体的边框中添加搜索框和按钮

    原文:WPF实用指南一:在WPF窗体的边框中添加搜索框和按钮 在边框中加入一些元素,在应用程序的界面设计中,已经开始流行起来.特别是在浏览器(Crome,IE,Firefox,Opera)中都有应用. ...

  5. ef core code first from exist db

    目标 为现有数据库生成新的连接,允许只选择部分表 可以处理一些很怪的需求,比如EF升级EF Core(这个可能有其他解),EF.EF Core同时连接一个数据库 我遇到的问题是: 原项目是.net f ...

  6. InitializeComponent无法识别的问题

    学习Xamarin官方文档的时候,Xamarin.Forms的开始篇一直在用ContentPage讲解自己一直是创建Page,然后手动修改成继承于ContentPage,然后InitializeCom ...

  7. C#彩色艺术化二维码样式设计(仅说思路)

    原文:C#彩色艺术化二维码样式设计(仅说思路) 仅讲思路,想要源码的请绕道.   一.样式 1.先看各种二维码的样式吧: (1)最简单的样式--黑白样式,如下图: 图1  最平常见到的二维码样式(如果 ...

  8. 读BeautifulSoup官方文档之html树的搜索(1)

    之前介绍了有关的四个对象以及他们的属性, 但是一般情况下要在杂乱的html中提取我们所需的tag(tag中包含的信息)是比较复杂的, 现在我们可以来看看到底有些什么搜索的方法. 最主要的两个方法当然是 ...

  9. SqlServer 禁止架构更改的复制中手动修复使发布和订阅中分别增加的字段同步

    原文:SqlServer 禁止架构更改的复制中手动修复使发布和订阅中分别增加的字段同步 由于之前的需要,禁止了复制架构更改,以至在发布中添加一个字段,并不会同步到订阅中,而现在又在订阅中添加了一个同名 ...

  10. Android零基础入门第40节:自定义ArrayAdapter

    原文:Android零基础入门第40节:自定义ArrayAdapter ListView用起来还是比较简单的,也是Android应用程序中最重要的一个组件,但其他ListView可以随你所愿,能够完成 ...