Skip to main content

用于在测试时控制查询计数的 Django 工具包

项目描述

https://badge.fury.io/py/django-test-query-counter.svg https://travis-ci.org/sophilabs/django-test-query-counter.svg?branch=master https://codecov.io/gh/sophilabs/django-test-query-counter/branch/master/graph/badge.svg 标识

一个 Django 工具包,用于在测试时控制查询计数。它控制测试中完成的查询数量保持在测试运行之间的特定阈值以下。当与 Jenkins 或 Travis 等 CI 配对以控制每次提交时特别有用,不会显着降低数据库速度。

要求

  • 蟒蛇 3

  • 姜戈

文档

完整的文档位于https://django-test-query-counter.readthedocs.io

安装

有多种方法可以将其安装到您的项目中

将此存储库克隆到您的项目中:

git clone https://github.com/sophilabs/django-test-query-counter.git

下载 zip 文件并解压缩:

wget https://github.com/sophilabs/django-test-query-counter/archive/master.zip
unzip master.zip

使用 pip 安装:

pip install django-test-query-counter

将其添加到您的INSTALLED_APPS

INSTALLED_APPS = (
    ...
    'test_query_count',
    ...
)

用法

像你一样运行你的 django 测试。运行 带有两个文件query_count.jsonquery_count_detail.json的报告目录后。

要检查您的测试查询计数运行:

$ python manage.py check_query_count

然后您会看到如下输出(如果您至少运行了两次测试):

All Tests API Queries are below the allowed threshold.

如果当前测试运行的查询比上一次多,它会告诉您:

There are test cases with API calls that exceeded threshold:

    In test case app.organizations.tests.api.test_division_api.DivisionViewTest.test_bulk_create_division, POST /api/divisions. Expected at most 11 queries but got 15 queries
    In test case app.shipments.tests.api.test_leg_api.LegViewTest.test_create_bulk_leg, POST /api/legs. Expected at most 59 queries but got 62 queries
    In test case app.plans.tests.functional.test_plan_api.PlannedDatesTest.test_unassign_and_assign_driver_to_leg, POST /api/assignments/assign-driver. Expected at most 261 queries but got 402 queries
CommandError: There was at least one test with an API call excedding the allowed threshold.

配置

您可以通过在设置文件中将 TEST_QUERY_COUNTER定义为字典来自定义测试查询计数的工作方式。以下代码显示了一个示例

TEST_QUERY_COUNTER = {
    # Global switch
    'ENABLE': True,

    # Paths where the count files are generated (relative to the current
    # process dir)
    'DETAIL_PATH': 'reports/query_count_detail.json',
    'SUMMARY_PATH': 'reports/query_count.json',

    # Tolerated percentage of count increase on successive
    # test runs.A value of 0 prevents increasing queries altoghether.
    'INCREASE_THRESHOLD': 10
}

排除测试

可以使用 @exclude_query_count装饰器为计数排除单个测试或类。例如

# To exclude all methods in the class
@exclude_query_count()
class AllTestExcluded(TestCase):
    def test_foo(self):
        self.client.get('path-1')

    def test_foo(self):
        self.client.get('path-2')

# To exclude one test only
class OneMethodExcluded():
    def test_foo(self):
        self.client.get('path-1')

    @exclude_query_count()
    def test_foo(self):
        self.client.get('path-2')

更具体地说,exclude_query_count接受参数以通过路径、方法或计数有条件地排除查询计数。排除路径的路径或正则表达式。该方法指定要排除的方法的正则表达式,并且计数是允许的最小查询数。与“计数”更少或相同数量的请求将被排除在外。

例如:

class Test(TestCase):
    @exclude_query_count(path='url-2')
    def test_exclude_path(self):
        self.client.get('/url-1')
        self.client.post('/url-2')

    @exclude_query_count(method='post')
    def test_exclude_method(self):
        self.client.get('/url-1')
        self.client.post('/url-2')

    @exclude_query_count(count=2)
    def test_exclude_count(self):
        #  succesive urls requests are additive
        for i in range(3):
            self.client.get('/url-1')

实施到您的 CI

目前,查询计数在本地工作。但是,当它与Jenkins或其他 CI 集成时,它会大放异彩。您必须手动执行此操作:

要求

  • 詹金斯有一个工作来构建你的项目。

从现在开始,假设您的工作在http://127.0.0.1:8080/job/ZAP_EXAMPLE_JOB/可用。

  1. 激活构建存档:转到作业配置页面并添加存档工件构建构建后操作。

    Jenkins Post Build Action 显示存档工件示例
  2. 将文件中的reports/query_count.json设置为存档路径

  3. 创建一个新的 Django 自定义命令来对归档的 Jenkins 文件运行验证。例如:

    from urllib.request import urlretrieve
    from django.core.management import BaseCommand, CommandError
    from django.conf import settings
    from test_query_counter.apps import RequestQueryCountConfig
    from test_query_counter.query_count import QueryCountEvaluator
    
    
    class Command(BaseCommand):
        JENKINS_QUERY_COUNT = 'https://yourci/job/' \
                              'yourproject/lastSuccessfulBuild/' \
                              'artifact/app/reports/query_count.json'
    
        def handle(self, *args, **options):
            current_file_path = RequestQueryCountConfig.get_setting('SUMMARY_FILE')
    
            with open(current_file_path) as current_file, \
                    open(urlretrieve(self.JENKINS_QUERY_COUNT)[0]) as last_file:
                violations = QueryCountEvaluator(10, current_file,last_file).run()
    
                if violations:
                    raise CommandError('There was at least one test with an API '
                                       'call excedding the allowed threshold.')
  4. 添加构建步骤以运行此命令:

    Jenkins Build Action 显示脚本操作

    之后,它将运行良好,如果任何查询计数超过限制,构建将失败。

去做

  • 在query_count_detail.json中包含对堆栈跟踪的支持。

  • 生成已执行查询的 HTML 报告。

  • 使查询计数可配置

  • 包括开箱即用的 Jenkins 支持(使用django_jenkins

运行测试

代码真的有效吗?

source <YOURVIRTUALENV>/bin/activate
(myenv) $ pip install tox
(myenv) $ tox

执照

PySchool 已获得 MIT 许可。版权所有 (c) 2017 Sophilabs, Inc.

学分

https://s3.amazonaws.com/sophilabs-assets/logo/logo_300x66.gif

该工具由 Sophilabs, Inc. 维护和资助。sophilabs 的名称和徽标是 sophilabs, Inc. 的商标。

用于渲染此包的工具:

历史

0.1.0 (2017-07-10)

  • PyPI 上的第一个版本。

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

django-test-query-counter-0.1.0.tar.gz (13.0 kB 查看哈希)

已上传 source