Sentry 测试指南 - 开发者贡献
在 Sentry 的 CI 流程中,我们运行多种测试以确保代码质量。本文档将介绍一些特定的帮助函数,并提供关于如何为新功能编写测试的指导。
环境设置
验收和 Python 测试需要一组有效的开发服务。建议使用这些服务来确保所需的服务正在运行。如果您同时进行本地测试,则需使用 --project 标志区分卷:
# 关闭本地测试服务
sentry devservices down
# 启动带有 test 前缀的服务
sentry devservices up --project test
# 检查测试容器状态
docker ps --format '{{.Names}}'
# 完成测试后重启本地服务器
sentry devservices down --project test && sentry devservices up
Python 测试
Sentry 使用 pytest 和 Django 的测试工具。我们扩展了这些工具,添加了一些基础测试用例(位于 sentry.testutils.cases 中)。
执行 pytest
# 运行目录下的所有测试 pytest tests/sentry/api/endpoints/ # 运行符合模式的所有文件中的测试 pytest tests/sentry/api/endpoints/test_organization_*.py # 运行单个文件中的所有测试 pytest tests/sentry/api/endpoints/test_organization_group_index.py # 运行单个测试方法 pytest tests/snuba/api/endpoints/test_organization_events_distribution.py::OrganizationEventsDistributionEndpointTest::test_this_thing # 根据子字符串过滤测试 pytest tests/snuba/api/endpoints/test_organization_events_distribution.py -k method_name
测试数据生成
Sentry 提供了一套工厂辅助方法来帮助构建测试数据:
from sentry.testutils.helpers.datetime import before_now
from sentry.utils.samples import load_data
def test_query(self):
data = load_data("python", timestamp=before_now(minutes=1))
event = self.store_event(data, project_id=self.project.id)
选项与特性标志
def test_success(self):
with self.feature('organization:new-feature'):
with self.options({'option': 'value'}):
# 执行带特性标志的测试逻辑
# 禁用特性标志
with self.feature({'organization:new-feature': False}):
# 执行不带特性标志的测试逻辑
验收测试
验收测试使用 selenium 和 chromedriver 来模拟用户操作。它们覆盖了端点测试或 Jest 无法覆盖的工作流程。
运行验收测试
# 运行单个验收测试 pytest tests/acceptance/test_organization_group_index.py -k test_with_onboarding # 显示浏览器界面运行测试 pytest tests/acceptance/test_organization_group_index.py --no-headless=true -k test_with_onboarding # 截图并比较快照 SENTRY_SCREENSHOT=1 VISUAL_SNAPSHOT_ENABLE=1 pytest tests/acceptance/test_organization_group_index.py -k test_with_onboarding
Jest 测试
Jest 测试集为前端组件提供了单元测试和集成测试的支持。
API Mocking
# 运行 Jest 测试 yarn test # 运行单个 Jest 测试 yarn test tests/js/spec/views/issueList/overview.spec.js