惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
博客园 - 【当耐特】
Cloudbric
Cloudbric
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Attack and Defense Labs
Attack and Defense Labs
爱范儿
爱范儿
The Cloudflare Blog
腾讯CDC
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
云风的 BLOG
云风的 BLOG
Recent Announcements
Recent Announcements
C
Check Point Blog
Schneier on Security
Schneier on Security
S
Schneier on Security
J
Java Code Geeks
B
Blog RSS Feed
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
Stack Overflow Blog
Stack Overflow Blog
博客园_首页
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
A
About on SuperTechFans
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Google DeepMind News
Google DeepMind News
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
A
Arctic Wolf
S
Secure Thoughts
P
Palo Alto Networks Blog
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
博客园 - 三生石上(FineUI控件)
D
Darknet – Hacking Tools, Hacker News & Cyber Security
量子位
U
Unit 42
I
InfoQ
D
DataBreaches.Net
P
Privacy International News Feed
T
Troy Hunt's Blog
博客园 - 叶小钗
T
Threatpost
博客园 - Franky
K
Kaspersky official blog
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家
www.infosecurity-magazine.com
www.infosecurity-magazine.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Cisco Blogs

陈少文的网站

巨变与机遇的未来十年 Kubernetes 平台管理软件压力测试方案 使用镜像部署 Hexo 静态页面 终于等到你 - GitHub 镜像仓库服务(ghcr.io) 一起来学 Go --(6)Interface 一起来学 Go --(5)Goroutine 和 Channel 什么是函数式编程 如何在 Kubernetes 集群集成 Kata 柯里化与偏函数 使用 PyGithub 自动创建 Label 软件产品是团队能力的输出 Helm 2 、Helm 3 比较 IoT 变现 Kubernetes 中的 DNS 服务 国内的 Helm 镜像源 Harbor 使用自签证书支持 Https 访问 DevOps 工具链之 Prow 如何使用 kfctl 安装 Kubeflow VS Code 无法下载 Go 插件的工具包 工程师更应具有服务精神 你不知道的 Docker 使用技巧 使用 Docker 运行 Tensorflow 论中国 什么是左移 如何清空 Git 仓库全部历史记录 一禅小和尚 有风吹过厨房 时间的玫瑰 如何在 CentOS 安装 GPU 驱动 开发 Tips(19) 使用 Velero 备份 Kubernetes 集群 Kubernetes Cheat Sheet 开发 Tips(18) 如何构建一个 Java 工程 开发 Tips(17) KubeSpray 安装 Kubernetes 报错 ip in ansible_all_ipv4_addresses 基于 Kubernetes 和 Jenkins 搭建自动化测试系统 在 Kubernetes 上动态创建 Jenkins Slave 使用 Jenkins 进行服务拨测 开发 Tips(16) Kubernetes 签发 Ingress 证书及日常故障运维 Kubernetes 中 Deployment 的基本操作 Kubernetes 中的证书 如何使用 KubeBuilder 开发一个 Operator Kubernetes 1.6.0 安装问题汇总 镜像管理工具 -- Harbor 开发 Tips(15) Docker 如何拉取镜像 开发 Tips(14) 使用 Helm 安装 harbor 开发 Tips(13) 使用 S2I 构建云原生应用 在 Kubernetes 中使用 emptyDir、hostPath、localVolume 开发 Tips(12) 开发 Tips(11) 代码质量分析工具 SonarQube 使用 Kubeadm 安装 Kubernetes 集群 一起来学 Go --(4)常用函数 Kubernetes 中的 Ceph Kubernetes 之 Volumes Kubernetes 之 Labels、Selectors 开发 Tips(10) 开源正在重构商业模式 Kubernetes 之网络 Kubernetes 之 API 使用 Helm 和 Operator 快速部署 Prometheus Kubernetes 复杂有状态应用管理框架 -- Operator Kubernetes 的包管理器 -- Helm 一起来学 Go --(3)Go Modules 如何一步一步地优化博客方案 kubectl 实用指南 Kubernetes 中的基本概念 搭建远程 Kubernetes 开发环境 大公司和小公司的 ToB 思路 开发 Tips(9) Go 入门指南 一起来学 Go --(2)数据与逻辑结构 如何预防 Web 富文本中的 XSS 攻击 django-xss-cleaner 云工作时代 一起来学 Go --(1)背景与特点 SaaS 开发团队的不同阶段 你不知道的 Git 使用技巧 输出既服务 微服务设计 继续奔跑 开发 Tips(8) 从账户安全到二次验证 Django 性能之数据库查询优化 Django 性能之分库分表 敏捷开发之研发流程 打造一致性的团队 开发 Tips(7) Pytest 进阶学习之 Mock PaaS 部署之 buildpack Go 开发配置 领域输出才是 PaaS 的核心竞争力 开发 Tips(6) 如何使用 Jenkins、Docker、GitLab 搭建 Django 自动化部署流程 开发 Tips(5)
Pytest 入门学习
微信公众号 · 2018-12-29 · via 陈少文的网站

Please enable Javascript to view the contents

Pytest 测试框架使用简单、插件丰富、功能强大,被广泛用于 Python 自动化测试。本文主要介绍一些 Pytest 的基本概念和使用方法。

1. 运行机制

第一步,Pytest 从命令行或文件中读取配置

第二步,在指定目录下查找并导入 conftest.py 文件

第三步,查找满足匹配条件的测试文件,通常是 test_ 开头的 py 文件

第四步,执行 session 或 module 类型的 fixture

第四步,查找并执行类、函数中,定义的测试用例

2. pytest.ini 和 conftest.py 文件

首先看下测试的文件组织方式:

1
2
3
4
5
6
7
8
/ -
  | - pytest.ini  # pytest 的配置文件
  | - tests
    |
    | - conftest.py  # 全局通用的配置和功能
    | - fun_module   # 某个模块的测试
          | - test_a.py  # 该模块下的测试
          | - conftest.py  # 该模块下通用的配置和功能

执行 Pytest 时,不仅可以使用命令行传递运行时参数,还可以使用配置文件。Pytest 查找配置文件的顺序是:

1
2
3
4
5
path/pytest.ini
path/setup.cfg     # must also contain [pytest] section to match
path/tox.ini       # must also contain [pytest] section to match
pytest.ini
...                # all the way down to the root

通常在项目下放置 pytest.ini 文件,配置相关参数即可。

pytest.ini:

1
2
3
4
5
6
7
[pytest]
# 指定测试目录
testpaths  = tests
# 指定测试用例文件的命名格式
python_files = test_*.py
# 指定 conftest 文件的路径
pytest_plugins = tests

tests/conftest.py 全局依赖的配置

1
2
def pytest_configure():
    pass

运行测试时,执行命令:

3. pytest.fixture

fixture 是 Pytest 引入的概念,是 Pytest 提供的强大功能之一。下面来看看具体的用法:

3.1 直接作为常量使用

1
2
3
4
5
6
@pytest.fixture()
def remote_api():
    return 'success'

def test_remote_api(remote_api):
    assert remote_api == 'success'

3.2 作为前置函数运行

fixture 允许在执行测试用例之前,先执行一些准备动作。

1
2
3
4
5
6
7
8
9
import pytest

@pytest.fixture()
def before():
    pass

@pytest.mark.usefixtures("before")
def test_1():
    pass

通过 autouse 和 scope,可以完成很多测试用例的准备工作。

3.3 作用域 - scope

通过 scope 参数声明作用域,可选项有四个,默认值为 function:

  • function,函数级,每个测试函数都会执行一次
  • class, 类级别,每个测试类执行一次,所有方法都可以使用
  • module,模块级,每个模块执行一次,模块内函数和方法都可使用
  • session,会话级,一次测试只执行一次,所有被找到的函数和方法都可用
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@pytest.fixture(scope='function')
def func_scope():
    pass

@pytest.fixture(scope='module')
def mod_scope():
    pass

@pytest.fixture(scope='session')
def sess_scope():
    pass

@pytest.fixture(scope='class')
def class_scope():
    pass

4. pytest.mark

pytest.mark 的作用是对测试用例进行标记,从而更精细化地控制测试用例。

marker 不需要事先定义好就能使用,下面是一个例子:

1
2
3
4
5
6
7
import pytest

A = pytest.mark.A

@A
def test_A():
    assert True

一些内置的 marker :

  • skip,跳过被装饰的测试用例
  • skipif,传递一个条件判断,满足时跳过测试
  • xfail,如果执行失败则认为是通过,成功则认为失败
  • parametrize,批量给测试用例提供数据。如果 parametrize 的参数名称和 fixture 名称一样,会覆盖 fixture。
1
2
3
4
5
6
@pytest.mark.parametrize('name',
                      ['12345',
                       'abcdef',
                       '0a1b2c3'])
def test_name_length(passwd):
    assert len(passwd) == 6

5. 常用插件

5.1 pytest-cov

pytest-cov 是一个自动检测测试覆盖率的插件。使用示例:

1
# pytest --cov=myproj tests/

5.2 pytest-mock

mock 是为了屏蔽一些依赖项。依赖项应该有单独的测试用例,每一个测试只需要关注自身功能是否正常。使用示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import os

class UnixFS:

    @staticmethod
    def rm(filename):
        os.remove(filename)

def test_unix_fs(mocker):
    mocker.patch('os.remove')
    UnixFS.rm('file')
    os.remove.assert_called_once_with('file')

5.3 pytest-html

pytest-html 是一个能自动生成 HTML 格式测试报告的插件。使用示例:

1
# pytest --html=report.html

5.4 pytest-django

pytest-django 为 Django 应用和项目添加了 Pytest 支持。具体来说,pytest-django 引入了使用 pytest fixture 测试 Django 项目的能力,并且比标准的 Django 测试套件运行得更快。


微信公众号