pytest、unittest、Django 和 Nose 的快照测试
项目描述
快照测试

快照测试是一种无需编写实际测试用例即可测试 API 的方法。
- 快照是 API 的单一状态,保存在文件中。
- 您有一组 API 端点的快照。
- 添加新功能后,您可以为更新的 API自动生成新快照。
安装
$ pip install snapshottest
与 unittest/nose 一起使用
from snapshottest import TestCase
class APITestCase(TestCase):
def test_api_me(self):
"""Testing the API for /me"""
my_api_response = api.client.get('/me')
self.assertMatchSnapshot(my_api_response)
# Set custom snapshot name: `gpg_response`
my_gpg_response = api.client.get('/me?gpg_key')
self.assertMatchSnapshot(my_gpg_response, 'gpg_response')
如果要自动更新快照,可以使用nosetests --snapshot-update.
检查单元测试示例。
与 pytest 一起使用
def test_mything(snapshot):
"""Testing the API for /me"""
my_api_response = api.client.get('/me')
snapshot.assert_match(my_api_response)
# Set custom snapshot name: `gpg_response`
my_gpg_response = api.client.get('/me?gpg_key')
snapshot.assert_match(my_gpg_response, 'gpg_response')
如果要自动更新快照,可以使用--snapshot-updateconfig.
检查Pytest 示例。
与 django 一起使用
添加到您的设置:
TEST_RUNNER = 'snapshottest.django.TestRunner'
要创建您的快照测试:
from snapshottest.django import TestCase
class APITestCase(TestCase):
def test_api_me(self):
"""Testing the API for /me"""
my_api_response = api.client.get('/me')
self.assertMatchSnapshot(my_api_response)
如果要自动更新快照,可以使用python manage.py test --snapshot-update. 检查Django 示例。
禁用终端颜色
设置环境变量ANSI_COLORS_DISABLED(任何值),例如
ANSI_COLORS_DISABLED=1 pytest
贡献
克隆此 repo 并为 snapshottest 配置 virtualenv(可选,但强烈推荐)后,通过运行确保安装依赖项:
make install
开发完成后,可以通过运行来评估完整的测试套件:
make lint
# and
make test
笔记
这个包在开玩笑快照测试中受到了很大的启发。
使用此软件包的原因
大部分内容取自Jest 快照博文。
我们希望尽可能轻松地编写有用的良好测试。我们观察到,当为工程师提供现成的工具时,他们最终会编写更多的测试,这反过来会产生稳定和健康的代码库。
然而,工程师经常花费比组件本身更多的时间来编写测试。结果,许多人完全停止编写测试,最终导致不稳定。
移动应用程序的典型快照测试用例会呈现 UI 组件,截取屏幕截图,然后将其与测试旁边存储的参考图像进行比较。如果两个图像不匹配,则测试将失败:要么更改意外,要么屏幕截图需要更新到新版本的 UI 组件。
使用 SnapshotTest 进行快照测试
在测试 API 时可以采用类似的方法。您可以使用测试渲染器为您的 API 响应快速生成可序列化的值,而不是渲染图形 UI,这需要构建整个应用程序。
执照
项目详情
下载文件
下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。
源分布
snapshottest-0.6.0.tar.gz
(22.6 kB
查看哈希)
内置分布
snapshottest-0.6.0-py2.py3-none-any.whl
(16.5 kB
查看哈希)