前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pytest的一些实用技巧

Pytest的一些实用技巧

原创
作者头像
杜逸先
发布2018-12-27 14:14:20
1.1K0
发布2018-12-27 14:14:20
举报

pytest.fixture()的作用域选择

:arg scope: the scope for which this fixture is shared, one of "function" (default), "class", "module","package" or "session".

代码语言:txt
复制
import pytest


@pytest.fixture()
def new_one():
    yield dict(a=1, b=2)


@pytest.fixture(scope='module')
def always_one():
    yield dict(a=1, b=2)


def test1(new_one:dict, always_one:dict):
    assert new_one'a' == 1
    assert always_one'a' == 1
    new_one'a' = -1
    always_one'a' = -1


def test2(new_one:dict, always_one:dict):
    assert new_one'a' == 1
    assert always_one'a' == 1

测试有异常抛出

代码语言:txt
复制
import pytest


def test():
    with pytest.raise(KeyError) as error:
        data = dict(a=1, b=2)
        data.pop('c')
    assert 'c' in str(error)

要注意as出的error并不是实际上抛出的异常,不能使用自定义异常的方法和属性,一般只检查str(error)

setup.cfg里的一些配置

代码语言:txt
复制
[tool:pytest]
python_paths = . ;好在根目录下运行py.test的时候扫描到需要测试的包
norecursedirs = .git .tox venv* requirements*; 不扫描的目录
python_files = test*.py ;测试代码
filterwarnings =
    ignore::DeprecationWarning ;在输出中过滤掉特定的警告信息

配合pytest-cov库进行代码覆盖率检查

安装pytest-cov库(依赖于coverage库)后可以很方便地进行代码覆盖率的配置。

代码语言:txt
复制
py.test --cov=app --cov-report=xml --cov-report=html

网页版的代码覆盖率报告在htmlcov目录下。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • pytest.fixture()的作用域选择
  • 测试有异常抛出
  • setup.cfg里的一些配置
  • 配合pytest-cov库进行代码覆盖率检查
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档