├── .coveragerc ├── .editorconfig ├── .github └── ISSUE_TEMPLATE.md ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── archive-artifact.png ├── build-action.png ├── cop.sh ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── logo.png ├── manage.py ├── requirements.txt ├── requirements_dev.txt ├── requirements_test.txt ├── runtests.py ├── setup.cfg ├── setup.py ├── test_query_counter ├── __init__.py ├── apps.py ├── management │ ├── __init__.py │ └── commands │ │ ├── __init__.py │ │ └── check_query_count.py ├── manager.py ├── middleware.py ├── models.py └── query_count.py ├── tests ├── __init__.py ├── settings.py ├── test_app_config.py ├── test_middleware.py ├── test_query_count_containers.py ├── test_query_count_evaluator.py ├── test_query_count_runner.py ├── urls.py └── views.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = true 3 | 4 | [report] 5 | omit = 6 | *site-packages* 7 | *tests* 8 | *.tox* 9 | show_missing = True 10 | exclude_lines = 11 | raise NotImplementedError 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.{py,rst,ini}] 12 | indent_style = space 13 | indent_size = 4 14 | 15 | [*.{html,css,scss,json,yml}] 16 | indent_style = space 17 | indent_size = 2 18 | 19 | [*.md] 20 | trim_trailing_whitespace = false 21 | 22 | [Makefile] 23 | indent_style = tab 24 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * Django API Query Count version: 2 | * Django version: 3 | * Python version: 4 | * Operating System: 5 | 6 | ### Description 7 | 8 | Describe what you were trying to get done. 9 | Tell us what happened, what went wrong, and what you expected to happen. 10 | 11 | ### What I Did 12 | 13 | ``` 14 | Paste the command(s) you ran and the output. 15 | If there was a crash, please include the traceback here. 16 | ``` 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | __pycache__ 3 | 4 | # C extensions 5 | *.so 6 | 7 | # Packages 8 | *.egg 9 | *.egg-info 10 | dist 11 | build 12 | eggs 13 | parts 14 | bin 15 | var 16 | sdist 17 | develop-eggs 18 | .installed.cfg 19 | lib 20 | lib64 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | htmlcov 30 | 31 | # Translations 32 | *.mo 33 | 34 | # Mr Developer 35 | .mr.developer.cfg 36 | .project 37 | .pydevproject 38 | 39 | # Pycharm/Intellij 40 | .idea 41 | 42 | # Complexity 43 | output/*.html 44 | output/*/index.html 45 | 46 | # Sphinx 47 | docs/_build 48 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | 3 | language: python 4 | 5 | python: 6 | - "3.5" 7 | 8 | env: 9 | - TOX_ENV=py35-django-18 10 | - TOX_ENV=py34-django-18 11 | - TOX_ENV=py33-django-18 12 | - TOX_ENV=py27-django-18 13 | - TOX_ENV=py35-django-19 14 | - TOX_ENV=py34-django-19 15 | - TOX_ENV=py27-django-19 16 | - TOX_ENV=py35-django-110 17 | - TOX_ENV=py34-django-110 18 | - TOX_ENV=py27-django-110 19 | 20 | matrix: 21 | fast_finish: true 22 | 23 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 24 | install: pip install -r requirements_test.txt 25 | 26 | # command to run tests using coverage, e.g. python setup.py test 27 | script: tox -e $TOX_ENV 28 | 29 | after_success: 30 | - codecov -e TOX_ENV 31 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Ignacio Avas 9 | 10 | Contributors 11 | ------------ 12 | 13 | None yet. Why not be the first? 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/sophilabs/django-test-query-counter/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | Django API Query Count could always use more documentation, whether as part of the 40 | official Django API Query Count docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github 47 | .com/sophilabs/django-test-query-counter/issues. 48 | 49 | If you are proposing a feature: 50 | 51 | * Explain in detail how it would work. 52 | * Keep the scope as narrow as possible, to make it easier to implement. 53 | * Remember that this is a volunteer-driven project, and that contributions 54 | are welcome :) 55 | 56 | Get Started! 57 | ------------ 58 | 59 | Ready to contribute? Here's how to set up `django-test-query-counter` for 60 | local 61 | development. 62 | 63 | 1. Fork the `django-test-query-counter` repo on GitHub. 64 | 2. Clone your fork locally:: 65 | 66 | $ git clone git@github.com:your_name_here/django-test-query-counter.git 67 | 68 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 69 | 70 | $ mkvirtualenv django-test-query-counter 71 | $ cd django-test-query-counter/ 72 | $ python setup.py develop 73 | 74 | 4. Create a branch for local development:: 75 | 76 | $ git checkout -b name-of-your-bugfix-or-feature 77 | 78 | Now you can make your changes locally. 79 | 80 | 5. When you're done making changes, check that your changes pass flake8 and the 81 | tests, including testing other Python versions with tox:: 82 | 83 | $ flake8 test_query_counter tests 84 | $ python setup.py test 85 | $ tox 86 | 87 | To get flake8 and tox, just pip install them into your virtualenv. 88 | 89 | 6. Commit your changes and push your branch to GitHub:: 90 | 91 | $ git add . 92 | $ git commit -m "Your detailed description of your changes." 93 | $ git push origin name-of-your-bugfix-or-feature 94 | 95 | 7. Submit a pull request through the GitHub website. 96 | 97 | Pull Request Guidelines 98 | ----------------------- 99 | 100 | Before you submit a pull request, check that it meets these guidelines: 101 | 102 | 1. The pull request should include tests. 103 | 2. If the pull request adds functionality, the docs should be updated. Put 104 | your new functionality into a function with a docstring, and add the 105 | feature to the list in README.rst. 106 | 3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check 107 | https://travis-ci.org/sophilabs/django-test-query-counter/pull_requests 108 | and make sure that the tests pass for all supported Python versions. 109 | 110 | Tips 111 | ---- 112 | 113 | To run a subset of tests:: 114 | 115 | $ python runtests.py tests.test_test_query_counter 116 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 0.1.0 (2017-07-10) 7 | ++++++++++++++++++ 8 | 9 | * First release on PyPI. 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | MIT License 3 | 4 | Copyright (c) 2017, Sophilabs Inc. 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | recursive-include test_query_counter *.html *.png *.gif *js *.css *jpg *jpeg *svg *py 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs help 2 | .DEFAULT_GOAL := help 3 | define BROWSER_PYSCRIPT 4 | import os, webbrowser, sys 5 | try: 6 | from urllib import pathname2url 7 | except: 8 | from urllib.request import pathname2url 9 | 10 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 11 | endef 12 | export BROWSER_PYSCRIPT 13 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 14 | 15 | help: 16 | @perl -nle'print $& if m{^[a-zA-Z_-]+:.*?## .*$$}' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-25s\033[0m %s\n", $$1, $$2}' 17 | 18 | clean: clean-build clean-pyc 19 | 20 | clean-build: ## remove build artifacts 21 | rm -fr build/ 22 | rm -fr dist/ 23 | rm -fr *.egg-info 24 | 25 | clean-pyc: ## remove Python file artifacts 26 | find . -name '*.pyc' -exec rm -f {} + 27 | find . -name '*.pyo' -exec rm -f {} + 28 | find . -name '*~' -exec rm -f {} + 29 | 30 | lint: ## check style with flake8 31 | flake8 test_query_counter tests 32 | 33 | test: ## run tests quickly with the default Python 34 | python runtests.py tests 35 | 36 | test-all: ## run tests on every Python version with tox 37 | tox 38 | 39 | coverage: ## check code coverage quickly with the default Python 40 | coverage run --source test_query_counter runtests.py tests 41 | coverage report -m 42 | coverage html 43 | open htmlcov/index.html 44 | 45 | docs: ## generate Sphinx HTML documentation, including API docs 46 | rm -f docs/django-test-query-counter.rst 47 | rm -f docs/modules.rst 48 | sphinx-apidoc -o docs/ test_query_counter 49 | $(MAKE) -C docs clean 50 | $(MAKE) -C docs html 51 | $(BROWSER) docs/_build/html/index.html 52 | 53 | release: clean ## package and upload a release 54 | python setup.py sdist upload 55 | python setup.py bdist_wheel upload 56 | 57 | sdist: clean ## package 58 | python setup.py sdist 59 | ls -l dist 60 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============================= 2 | Django Test Query Counter 3 | ============================= 4 | 5 | .. image:: https://badge.fury.io/py/django-test-query-counter.svg 6 | :target: https://badge.fury.io/py/django-test-query-counter 7 | 8 | .. image:: https://travis-ci.org/sophilabs/django-test-query-counter.svg?branch=master 9 | :target: https://travis-ci.org/sophilabs/django-test-query-counter 10 | 11 | .. image:: https://codecov.io/gh/sophilabs/django-test-query-counter/branch/master/graph/badge.svg 12 | :target: https://codecov.io/gh/sophilabs/django-test-query-counter 13 | 14 | 15 | .. image:: logo.png 16 | :width: 200 17 | :alt: Logo 18 | :align: center 19 | 20 | A Django Toolkit for controlling Query count when testing. It controls the 21 | number of queries done in the tests stays below a particular threshold between 22 | Test Runs.Specially useful when paired with a CI like Jenkins or Travis to 23 | control each commit doesn't slow down the Database considerably. 24 | 25 | Requirements 26 | ------------ 27 | 28 | * Python 3 29 | * Django 30 | 31 | Documentation 32 | ------------- 33 | 34 | The full documentation is at https://django-test-query-counter.readthedocs.io. 35 | 36 | Installation 37 | ------------- 38 | 39 | There are ways to install it into your project 40 | 41 | Clone this repository into your project: 42 | 43 | .. code-block:: bash 44 | 45 | git clone https://github.com/sophilabs/django-test-query-counter.git 46 | 47 | Download the zip file and unpack it: 48 | 49 | .. code-block:: bash 50 | 51 | wget https://github.com/sophilabs/django-test-query-counter/archive/master.zip 52 | unzip master.zip 53 | 54 | Install with pip: 55 | 56 | .. code-block:: bash 57 | 58 | pip install django-test-query-counter 59 | 60 | Add it to your `INSTALLED_APPS`: 61 | 62 | .. code-block:: python 63 | 64 | INSTALLED_APPS = ( 65 | ... 66 | 'test_query_counter', 67 | ... 68 | ) 69 | 70 | Usage 71 | ----- 72 | 73 | Run your django tests as you do. After the run the 74 | ``reports`` directory with two files ``query_count.json`` and 75 | ``query_count_detail.json``. 76 | 77 | To check your tests Query Counts run: 78 | 79 | ``$ python manage.py check_query_count`` 80 | 81 | Then you would see an output like the following one (if you at least ran the 82 | tests twice): 83 | 84 | .. code-block:: 85 | 86 | All Tests API Queries are below the allowed threshold. 87 | 88 | If the current test run had more queries than the last one, it will tell you: 89 | 90 | .. code-block:: 91 | 92 | There are test cases with API calls that exceeded threshold: 93 | 94 | 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 95 | 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 96 | 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 97 | CommandError: There was at least one test with an API call excedding the allowed threshold. 98 | 99 | Configuration 100 | ------------- 101 | 102 | You can customize how the Test Query Count works by defining ``TEST_QUERY_COUNTER`` 103 | in your settings file as a dictionary. The following code shows an example 104 | 105 | .. code-block:: python 106 | 107 | TEST_QUERY_COUNTER = { 108 | # Global switch 109 | 'ENABLE': True, 110 | 111 | # Paths where the count files are generated (relative to the current 112 | # process dir) 113 | 'DETAIL_PATH': 'reports/query_count_detail.json', 114 | 'SUMMARY_PATH': 'reports/query_count.json', 115 | 116 | # Tolerated percentage of count increase on successive 117 | # test runs.A value of 0 prevents increasing queries altoghether. 118 | 'INCREASE_THRESHOLD': 10 119 | } 120 | 121 | 122 | Excluding Tests 123 | --------------- 124 | 125 | Individual tests or classes can be excluded for the count using the 126 | ``@exclude_query_count`` decorator. For example 127 | 128 | .. code-block:: python 129 | 130 | # To exclude all methods in the class 131 | @exclude_query_count() 132 | class AllTestExcluded(TestCase): 133 | def test_foo(self): 134 | self.client.get('path-1') 135 | 136 | def test_foo(self): 137 | self.client.get('path-2') 138 | 139 | # To exclude one test only 140 | class OneMethodExcluded(): 141 | def test_foo(self): 142 | self.client.get('path-1') 143 | 144 | @exclude_query_count() 145 | def test_foo(self): 146 | self.client.get('path-2') 147 | 148 | 149 | More specifically, ``exclude_query_count`` accept parameters to conditionally 150 | exclude a query count by path, method or count. Where ``path`` the or regex of 151 | the excluded path(s). The ``method`` specifies the regex of the method(s) to 152 | exclude, and ``count`` is minimum number of queries tolerated. Requests with 153 | less or same amount as "count" will be excluded. 154 | 155 | For example: 156 | 157 | .. code-block:: python 158 | 159 | class Test(TestCase): 160 | @exclude_query_count(path='url-2') 161 | def test_exclude_path(self): 162 | self.client.get('/url-1') 163 | self.client.post('/url-2') 164 | 165 | @exclude_query_count(method='post') 166 | def test_exclude_method(self): 167 | self.client.get('/url-1') 168 | self.client.post('/url-2') 169 | 170 | @exclude_query_count(count=2) 171 | def test_exclude_count(self): 172 | # succesive urls requests are additive 173 | for i in range(3): 174 | self.client.get('/url-1') 175 | 176 | Implementing into your CI 177 | ------------------------- 178 | 179 | Currently the query count works locally. However, it shines when it is 180 | integrated with `Jenkins `_, or other CIs. You have to do 181 | this manually: 182 | 183 | Requirements 184 | 185 | * Jenkins with a Job that build you project. 186 | 187 | From now on let's suppose your job is available at ``http://127.0.0.1:8080/job/ZAP_EXAMPLE_JOB/``. 188 | 189 | 190 | 1. `Activate Build Archive`: Go to the job `configuration page `_ and add the `archive artifacts `_ build 191 | Post-build actions. 192 | 193 | .. image:: archive-artifact.png 194 | :alt: Jenkins Post Build Action showing an archive artifact example 195 | :align: center 196 | 197 | 2. Set ``reports/query_count.json`` in the files to archive path 198 | 199 | 3. Create a new Django custom Command to run the validation against the 200 | archived Jenkins file. For example: 201 | 202 | .. code-block:: python 203 | 204 | from urllib.request import urlretrieve 205 | from django.core.management import BaseCommand, CommandError 206 | from django.conf import settings 207 | from test_query_counter.apps import RequestQueryCountConfig 208 | from test_query_counter.query_count import QueryCountEvaluator 209 | 210 | 211 | class Command(BaseCommand): 212 | JENKINS_QUERY_COUNT = 'https://yourci/job/' \ 213 | 'yourproject/lastSuccessfulBuild/' \ 214 | 'artifact/app/reports/query_count.json' 215 | 216 | def handle(self, *args, **options): 217 | current_file_path = RequestQueryCountConfig.get_setting('SUMMARY_FILE') 218 | 219 | with open(current_file_path) as current_file, \ 220 | open(urlretrieve(self.JENKINS_QUERY_COUNT)[0]) as last_file: 221 | violations = QueryCountEvaluator(10, current_file,last_file).run() 222 | 223 | if violations: 224 | raise CommandError('There was at least one test with an API ' 225 | 'call excedding the allowed threshold.') 226 | 227 | 4. Add a build step to run this command: 228 | 229 | .. image:: build-action.png 230 | :alt: Jenkins Build Action showing the script action 231 | :align: center 232 | 233 | After that, it will run fine, and the build would fail if any Query count is over the limit. 234 | 235 | TODO 236 | ---- 237 | 238 | * Include support for stacktraces in ``query_count_detail.json``. 239 | * Generate an HTML report of executed Queries. 240 | * Make query count configurable 241 | * Include Jenkins support out of the box (using `django_jenkins`) 242 | 243 | Running Tests 244 | ------------- 245 | 246 | Does the code actually work? 247 | 248 | .. code-block:: bash 249 | 250 | source /bin/activate 251 | (myenv) $ pip install tox 252 | (myenv) $ tox 253 | 254 | License 255 | ------- 256 | 257 | Django Test Query Counter is MIT Licensed. Copyright (c) 2017 Sophilabs, Inc. 258 | 259 | 260 | Credits 261 | ------- 262 | 263 | .. image:: https://s3.amazonaws.com/sophilabs-assets/logo/logo_300x66.gif 264 | :target: https://sophilabs.co 265 | 266 | This tool is maintained and funded by Sophilabs, Inc. The names and logos for 267 | sophilabs are trademarks of sophilabs, inc. 268 | 269 | Tools used in rendering this package: 270 | 271 | * Cookiecutter_ 272 | * `cookiecutter-djangopackage`_ 273 | 274 | .. _Cookiecutter: https://github.com/audreyr/cookiecutter 275 | .. _`cookiecutter-djangopackage`: https://github.com/pydanny/cookiecutter-djangopackage 276 | -------------------------------------------------------------------------------- /archive-artifact.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sophilabs/django-test-query-counter/467419b40c6b2cd3f19047522ee25d843b73d768/archive-artifact.png -------------------------------------------------------------------------------- /build-action.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sophilabs/django-test-query-counter/467419b40c6b2cd3f19047522ee25d843b73d768/build-action.png -------------------------------------------------------------------------------- /cop.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | verbose=0 4 | base_directory=$(git rev-parse --show-toplevel) 5 | current_directory=$(pwd) 6 | branch=$(git rev-parse --abbrev-ref HEAD) 7 | npm_folder='app_client' 8 | public_folder='app_client' 9 | info_ok="👌 " 10 | info_fail="🔥 " 11 | isort='isort -sp ./.isort.cfg ' 12 | status_ok="👍 " 13 | status_fail="💥 " 14 | html_hint_exec='./app_client/node_modules/gulp-htmlhint/node_modules/htmlhint/bin/htmlhint --config app_client/.htmlhintrc' 15 | 16 | # Back to current folder on end 17 | trap "cd ${current_directory}" SIGINT SIGTERM EXIT 18 | cd "${base_directory}" 19 | 20 | # Override default execs, variables, etc... 21 | if [ -f "local.sh" ]; then 22 | source "local.sh" 23 | fi 24 | 25 | # Load files exceptions (only for HTML now) 26 | if [ -f "file_exceptions.sh" ]; then 27 | source "file_exceptions.sh" 28 | fi 29 | 30 | info () { 31 | show=verbose 32 | if [ -n "$4" ]; then 33 | show=$4 34 | fi 35 | if [ "${1}" -eq '0' ]; then 36 | if [ $show -eq 1 ] ; then 37 | printf '%b %b\n' "${info_ok}" "${2}" >&2 38 | fi 39 | else 40 | printf '%b %b\n' "${info_fail}" "${2}" >&2 41 | if [ -z $3 ] || [ $3 -eq 1 ] ; then 42 | exit 1 43 | fi 44 | fi 45 | } 46 | 47 | program_exists () { 48 | local ret='0' 49 | type $1 >/dev/null 2>&1 || { local ret='1'; } 50 | # throw error on non-zero return value 51 | if [ ! "${ret}" -eq '0' ]; then 52 | info 1 "Sorry, we cannot continue without ${1}, please install it first. ${2}" $3 53 | fi 54 | } 55 | 56 | containsElement () { 57 | local e 58 | for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done 59 | return 1 60 | } 61 | 62 | ############################################################################### 63 | # INSTALL 64 | ############################################################################### 65 | 66 | install () { 67 | cat > .git/hooks/pre-commit << 'EOF' 68 | base_directory=$(git rev-parse --show-toplevel) 69 | eval "${base_directory}/cop.sh pre-commit --verbose HEAD" 70 | EOF 71 | chmod +x .git/hooks/pre-commit 72 | info 0 "The pre-commit hook was installed." 0 $1 73 | 74 | cat > .git/hooks/commit-msg << 'EOF' 75 | base_directory=$(git rev-parse --show-toplevel) 76 | eval "${base_directory}/cop.sh commit-msg $@" 77 | EOF 78 | chmod +x .git/hooks/commit-msg 79 | info 0 "The commit-msg hook was installed." 0 $1 80 | } 81 | 82 | 83 | 84 | ############################################################################### 85 | # PRE COMMIT 86 | ############################################################################### 87 | 88 | function pre_commit () { 89 | 90 | # Execs 91 | if [ -z "${eslint_exec}" ]; then 92 | eslint_exec="npm run eslint --" 93 | fi 94 | 95 | # Protected branches: 96 | if [[ "$branch" == "master" || "$branch" == "dev" ]]; then 97 | printf "🔥 \e[31mYou CAN'T commit on branch ${branch}.\e[0m\n" 98 | exit 1 99 | fi 100 | 101 | check_py=1 102 | check_py_lint=0 103 | check_scss=1 104 | check_scss_lint=1 105 | check_js=1 106 | check_js_lint=1 107 | check_html=1 108 | check_images=1 109 | 110 | verbose=0 111 | exit_on_error=1 112 | 113 | while [ $# -gt 0 ] 114 | do 115 | case "$1" in 116 | 117 | --verbose) 118 | verbose=1 119 | shift 120 | ;; 121 | 122 | --no-exit) 123 | exit_on_error=0 124 | shift 125 | ;; 126 | 127 | --py) 128 | check_py=1 129 | shift 130 | ;; 131 | 132 | --no-py) 133 | check_py=0 134 | shift 135 | ;; 136 | 137 | --py-lint) 138 | check_py_lint=1 139 | shift 140 | ;; 141 | 142 | --no-py-lint) 143 | check_py_lint=1 144 | shift 145 | ;; 146 | 147 | --no-scss) 148 | check_scss=0 149 | shift 150 | ;; 151 | 152 | --no-scss-lint) 153 | check_scss_lint=0 154 | shift 155 | ;; 156 | 157 | --js) 158 | check_js=1 159 | shift 160 | ;; 161 | 162 | --no-js) 163 | check_js=0 164 | shift 165 | ;; 166 | 167 | --no-js-lint) 168 | check_js_lint=0 169 | shift 170 | ;; 171 | 172 | --html) 173 | check_html=1 174 | shift 175 | ;; 176 | 177 | --no-html) 178 | check_html=0 179 | shift 180 | ;; 181 | 182 | --images) 183 | check_images=1 184 | shift 185 | ;; 186 | 187 | --no-images) 188 | check_images=0 189 | shift 190 | ;; 191 | 192 | -*) 193 | echo "Invalid option: ${1}" 194 | exit 1 195 | ;; 196 | 197 | *) 198 | target=$1 199 | shift 200 | ;; 201 | esac 202 | done 203 | 204 | ignore=( 205 | '^_trash' 206 | '^docs' 207 | '^keys' 208 | 'api\.js$' 209 | '^extras' 210 | 'api\.js$' 211 | '^app/.*/migrations/' 212 | '^app/.*/vendor/' 213 | ) 214 | exclude=`python -c 'import sys;print("({})".format("|".join(sys.argv[1:])))' "${ignore[@]}"` 215 | 216 | # List files 217 | if [[ -n $target ]]; then 218 | if [[ $target =~ ^([0-9abcdef]{7,40})$ ]]; then 219 | files=`git show --pretty="format:" --name-only ${target} | grep -Ev ${exclude}` 220 | elif [[ $target =~ ^(HEAD)$ ]]; then 221 | files=`git diff --cached --name-only --diff-filter=AMR ${target} | grep -Ev ${exclude}` 222 | elif [[ $target =~ ^\.$ ]]; then 223 | files=`git ls-files| grep -Ev ${exclude}` 224 | else 225 | if [ ! -f $target ]; then 226 | echo "File not found: ${target}" 227 | exit 1 228 | fi 229 | files=$target 230 | fi 231 | else 232 | files=`git status --porcelain -uall | awk 'match($1, /R|RM/) {print $4; next} match($1, /A|M|MM|AM/) {print $2}' | grep -Ev ${exclude}` 233 | fi 234 | 235 | result=0 236 | 237 | status () { 238 | if [ "${3}" -eq '0' ]; then 239 | if [ $verbose -eq 1 ] || [ -n "${4}" ] ; then 240 | # printf "\e[32m ${2}\e[0m%b\n" >&2 241 | printf "${status_ok} \e[32m${2}\e[0m%b: ${1}\n" >&2 242 | fi 243 | else 244 | # printf " \e[31m❯ ${2}\e[0m%b\n" >&2 245 | printf "${status_fail} \e[31m${2}\e[0m%b: ${1}\n" >&2 246 | result=1 247 | if [ -z $exit_on_error ] || [ $exit_on_error -eq 1 ] ; then 248 | exit 1 249 | fi 250 | fi 251 | } 252 | 253 | 254 | # For each file... 255 | for file in $files; do 256 | if containsElement $file "${FILE_EXCEPTIONS[@]}"; then 257 | continue 258 | fi 259 | 260 | if [ ! -f $file ]; then 261 | continue 262 | fi 263 | 264 | # unresolved merge conflict 265 | cat "${file}" | grep -n -E "(^<<<<<<<\s|^=======\$|^>>>>>>>\s)" | grep -v "noqa" 266 | if [ $? -eq 0 ]; then 267 | status $file 'git-conflict' 1 268 | else 269 | status $file 'git-conflict' 0 270 | fi 271 | 272 | contains_super=`cat $file | grep '\ssuper([a-zA-Z]\+)'`; 273 | if [[ ! -z $contains_super ]]; then 274 | status $file 'contains-super-with-params' 1 275 | exit 1; 276 | fi 277 | 278 | # python 279 | if [ $check_py -eq 1 ] ; then 280 | if [[ $file =~ \.py$ ]]; then 281 | program_exists 'flake8' '(pip install flake8)' 282 | program_exists 'isort' '(pip install isort)' 283 | program_exists 'pylint' '(pip install pylint)' 284 | 285 | # filename format 286 | if [[ $file =~ (^|/)[a-z_0-9]+\.py$ ]] ; then 287 | status $file 'py-ff' 0 288 | else 289 | echo "Invalid filename format: {$file}" 290 | status $file 'py-ff' 1 291 | fi 292 | 293 | # isort 294 | ${isort} -ns __init__.py --check-only "${file}" 295 | if [ $? -eq '0' ]; then 296 | status $file 'py-isort' $? 297 | elif [[ $target =~ ^(HEAD)$ ]]; then 298 | ${isort} -ns __init__.py "${file}" 299 | ${isort} -ns __init__.py --check-only "${file}" 300 | git add "${file}" 301 | status $file 'py-isort-autofix' $? 1 302 | else 303 | status $file 'py-isort' $? 304 | fi 305 | 306 | # flake8 307 | flake8 "${file}" 308 | status $file 'py-flake8' $? 309 | 310 | # pylint 311 | if [ $check_py_lint -eq 1 ] ; then 312 | pylint --rcfile="${base_directory}/.pylintrc" "${file}" 313 | status $file 'py-pylint' $? 314 | fi 315 | 316 | # i18n_deprecated 317 | cat "${file}" | grep -o -n -E "gettext" 318 | if [ $? -eq 0 ]; then 319 | status $file 'py-i18n' 1 320 | else 321 | status $file 'py-i18n' 0 322 | fi 323 | 324 | # forgotten_prints 325 | noqa=`cat "${file}" | grep "noqa: print"` 326 | if [ $? -eq 1 ]; then 327 | cat "${file}" | grep -n -E "\bprint\s*\(" | grep -v "noqa" 328 | if [ $? -eq 0 ]; then 329 | status $file 'py-fp' 1 330 | else 331 | status $file 'py-fp' 0 332 | fi 333 | fi 334 | 335 | # forgotten_debbug_lines 336 | noqa=`cat "${file}" | grep "noqa: debug"` 337 | if [ $? -eq 1 ]; then 338 | cat "${file}" | grep -n -E "\bset_trace\s*\(" | grep -v "noqa" 339 | if [ $? -eq 0 ]; then 340 | status $file 'py-fd' 1 341 | else 342 | status $file 'py-fd' 0 343 | fi 344 | fi 345 | fi 346 | fi 347 | 348 | 349 | 350 | # scss 351 | if [ $check_scss -eq 1 ] ; then 352 | if [[ $file =~ \.scss$ ]]; then 353 | program_exists 'scss-lint' '(gem install scss-lint)' 354 | 355 | # scss: filename format 356 | if [[ $file =~ (^|/)_?[a-z0-9\-]+\.scss$ ]] ; then 357 | status $file 'scss-ff' 0 358 | else 359 | echo "Invalid filename format: {$file}" 360 | status $file 'scss-ff' 1 361 | fi 362 | 363 | # FIXME: Disabled, because is intented to be used with a prefixer 364 | # cat "${file}" | grep -v "\b@mixin cross-browser\b" | grep -o -n -E "\bcross-browser\b" 365 | # if [ $? -eq 0 ]; then 366 | # status $file 'scss-cb' 1 367 | # else 368 | # status $file 'scss-cb' 0 369 | # fi 370 | # 371 | # cat "${file}" | grep -o -n -E "\bcrossBrowser\b" 372 | # if [ $? -eq 0 ]; then 373 | # status $file 'scss-cb' 1 374 | # else 375 | # status $file 'scss-cb' 0 376 | # fi 377 | 378 | # scss-lint 379 | if [ $check_scss_lint -eq 1 ] ; then 380 | scss-lint --require "${base_directory}/extras/scss_linters/no_pointer_events.rb" "$file" 381 | status $file 'scss-lint' $? 382 | fi 383 | fi 384 | fi 385 | 386 | 387 | # js 388 | if [ $check_js -eq 1 ] ; then 389 | if [[ $file =~ \.js$ ]]; then 390 | 391 | # filename_format 392 | if [[ $file =~ (^|/)[a-z0-9\.\-]+\.js$ ]] ; then 393 | status $file 'js-ff' 0 394 | else 395 | echo "Invalid filename format: {$file}" 396 | status $file 'js-ff' 1 397 | fi 398 | 399 | # forgotten_log 400 | cat "${file}" | grep -o -n -E "\bconsole.log\b" | grep -v "noqa" 401 | if [ $? -eq 0 ]; then 402 | status $file 'js-fl' 1 403 | else 404 | status $file 'js-fl' 0 405 | fi 406 | 407 | # forgotten debugger 408 | cat "${file}" | grep -o -n -E "\bdebugger\b" | grep -v "noqa" 409 | if [ $? -eq 0 ]; then 410 | status $file 'js-debug' 1 411 | else 412 | status $file 'js-debug' 0 413 | fi 414 | 415 | # eslint 416 | if [ $check_js_lint -eq 1 ] ; then 417 | cd "$npm_folder" 418 | eval "${eslint_exec} ${file}" 419 | status $file 'js-eslint' $? 420 | cd - 421 | fi 422 | 423 | fi 424 | fi 425 | 426 | 427 | # HTML 428 | if [ $check_html -eq 1 ] ; then 429 | if [[ $file =~ \.html$ ]]; then 430 | 431 | # filename format 432 | regex="^$public_folder/" 433 | if [[ $file =~ $regex ]] ; then 434 | if [[ $file =~ (^|/)[a-z0-9\-]+\.html$ ]] ; then 435 | status $file 'html-ff' 0 '' 436 | else 437 | status $file 'html-ff' 1 "${file}" 438 | fi 439 | else 440 | if [[ $file =~ (^|/)[a-z0-9\_]+\.html$ ]] ; then 441 | status $file 'html-ff' 0 '' 442 | else 443 | status $file 'html-ff' 1 "${file}" 444 | fi 445 | fi 446 | 447 | # blocks_name_format 448 | cat "${file}" | grep -o -n -E "\{\%\s+block\s+[a-z0-9_]*[A-Z\-]+[a-z0-9_]*" 449 | if [ $? -eq 0 ]; then 450 | status $file 'html-block' 1 451 | else 452 | status $file 'html-block' 0 453 | fi 454 | 455 | # i18n_deprecated 456 | cat "${file}" | grep -o -n -E "\{\%\s+load\s+i18n\s+\%\}" 457 | if [ $? -eq 0 ]; then 458 | status $file 'html-i18n' 1 459 | else 460 | status $file 'html-i18n' 0 461 | fi 462 | 463 | # trans_deprecated 464 | cat "${file}" | grep -o -n -E "\{\%\s+trans\s+[^%]+" 465 | if [ $? -eq 0 ]; then 466 | status $file 'html-trans' 1 467 | else 468 | status $file 'html-trans' 0 469 | fi 470 | 471 | # htmlhint 472 | eval "${html_hint_exec} ${file}" 473 | status $file 'html-hint' $? 474 | 475 | fi 476 | fi 477 | 478 | 479 | # Images 480 | if [ $check_images -eq 1 ] ; then 481 | if [[ $file =~ \.(jpeg|gif|png|jpg)$ ]]; then 482 | 483 | status '🙏 \e[31mPLEASE: RENAME THE IMAGE FILE IF YOU MODIFIED IT.\e[0m' 'images-warn' 0 484 | 485 | # filename_format 486 | if [[ $file =~ (^|/)[a-z0-9\-]+\.(jpeg|gif|png|jpg)$ ]] ; then 487 | if [[ $file =~ \.(jpeg|jpg)$ ]]; then 488 | jpegoptim -m90 $file 489 | fi 490 | if [[ $file =~ \.(gif|png)$ ]]; then 491 | optipng $file 492 | fi 493 | status $file 'images-ff' 0 494 | else 495 | echo "Invalid filename format: {$file}" 496 | status $file 'images-ff' 1 497 | fi 498 | 499 | fi 500 | fi 501 | 502 | done 503 | 504 | if [ $result -eq 0 ] ; then 505 | echo "👮 < Move along. There's nothing to see here." 506 | fi 507 | 508 | exit $result 509 | } 510 | 511 | ############################################################################### 512 | # COMMIT MSG 513 | ############################################################################### 514 | 515 | function commit_msg () 516 | { 517 | return; 518 | 519 | # ./check_ticket.py ${line} 520 | # if [ $? -eq '1' ]; then 521 | # printf "🔥 \e[31mInvalid commit JIRA ticket: ${line}\e[0m \n" 522 | # 523 | # exit 1 524 | # fi 525 | 526 | } 527 | 528 | 529 | ############################################################################### 530 | # READ ARGS 531 | ############################################################################### 532 | 533 | install 0 534 | 535 | case "$1" in 536 | 537 | pre-commit) 538 | shift 539 | pre_commit $@ 540 | ;; 541 | 542 | commit-msg) 543 | shift 544 | commit_msg $@ 545 | ;; 546 | 547 | install) 548 | shift 549 | install 1 550 | ;; 551 | 552 | -*) 553 | pre_commit $@ 554 | ;; 555 | 556 | *) 557 | pre_commit $@ 558 | ;; 559 | esac 560 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # complexity documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | cwd = os.getcwd() 22 | parent = os.path.dirname(cwd) 23 | sys.path.append(parent) 24 | 25 | import test_query_counter 26 | 27 | # -- General configuration ----------------------------------------------------- 28 | 29 | # If your documentation needs a minimal Sphinx version, state it here. 30 | #needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be extensions 33 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'Django Test Query Count' 50 | copyright = u'2017, Sophilabs Inc.' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | version = test_query_counter.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = test_query_counter.__version__ 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | # If true, keep warnings as "system message" paragraphs in the built documents. 96 | #keep_warnings = False 97 | 98 | 99 | # -- Options for HTML output --------------------------------------------------- 100 | 101 | # The theme to use for HTML and HTML Help pages. See the documentation for 102 | # a list of builtin themes. 103 | html_theme = 'default' 104 | 105 | # Theme options are theme-specific and customize the look and feel of a theme 106 | # further. For a list of options available for each theme, see the 107 | # documentation. 108 | #html_theme_options = {} 109 | 110 | # Add any paths that contain custom themes here, relative to this directory. 111 | #html_theme_path = [] 112 | 113 | # The name for this set of Sphinx documents. If None, it defaults to 114 | # " v documentation". 115 | #html_title = None 116 | 117 | # A shorter title for the navigation bar. Default is the same as html_title. 118 | #html_short_title = None 119 | 120 | # The name of an image file (relative to this directory) to place at the top 121 | # of the sidebar. 122 | #html_logo = None 123 | 124 | # The name of an image file (within the static path) to use as favicon of the 125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 126 | # pixels large. 127 | #html_favicon = None 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | html_static_path = ['_static'] 133 | 134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 135 | # using the given strftime format. 136 | #html_last_updated_fmt = '%b %d, %Y' 137 | 138 | # If true, SmartyPants will be used to convert quotes and dashes to 139 | # typographically correct entities. 140 | #html_use_smartypants = True 141 | 142 | # Custom sidebar templates, maps document names to template names. 143 | #html_sidebars = {} 144 | 145 | # Additional templates that should be rendered to pages, maps page names to 146 | # template names. 147 | #html_additional_pages = {} 148 | 149 | # If false, no module index is generated. 150 | #html_domain_indices = True 151 | 152 | # If false, no index is generated. 153 | #html_use_index = True 154 | 155 | # If true, the index is split into individual pages for each letter. 156 | #html_split_index = False 157 | 158 | # If true, links to the reST sources are added to the pages. 159 | #html_show_sourcelink = True 160 | 161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 162 | #html_show_sphinx = True 163 | 164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 165 | #html_show_copyright = True 166 | 167 | # If true, an OpenSearch description file will be output, and all pages will 168 | # contain a tag referring to it. The value of this option must be the 169 | # base URL from which the finished HTML is served. 170 | #html_use_opensearch = '' 171 | 172 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 173 | #html_file_suffix = None 174 | 175 | # Output file base name for HTML help builder. 176 | htmlhelp_basename = 'django-test-query-counterdoc' 177 | 178 | 179 | # -- Options for LaTeX output -------------------------------------------------- 180 | 181 | latex_elements = { 182 | # The paper size ('letterpaper' or 'a4paper'). 183 | #'papersize': 'letterpaper', 184 | 185 | # The font size ('10pt', '11pt' or '12pt'). 186 | #'pointsize': '10pt', 187 | 188 | # Additional stuff for the LaTeX preamble. 189 | #'preamble': '', 190 | } 191 | 192 | # Grouping the document tree into LaTeX files. List of tuples 193 | # (source start file, target name, title, author, documentclass [howto/manual]). 194 | latex_documents = [ 195 | ('index', 'django-test-query-counter.tex', u'Django Test Query Count ' 196 | u'Documentation', 197 | u'Ignacio Avas', 'manual'), 198 | ] 199 | 200 | # The name of an image file (relative to this directory) to place at the top of 201 | # the title page. 202 | #latex_logo = None 203 | 204 | # For "manual" documents, if this is true, then toplevel headings are parts, 205 | # not chapters. 206 | #latex_use_parts = False 207 | 208 | # If true, show page references after internal links. 209 | #latex_show_pagerefs = False 210 | 211 | # If true, show URL addresses after external links. 212 | #latex_show_urls = False 213 | 214 | # Documents to append as an appendix to all manuals. 215 | #latex_appendices = [] 216 | 217 | # If false, no module index is generated. 218 | #latex_domain_indices = True 219 | 220 | 221 | # -- Options for manual page output -------------------------------------------- 222 | 223 | # One entry per manual page. List of tuples 224 | # (source start file, name, description, authors, manual section). 225 | man_pages = [ 226 | ('index', 'django-test-query-counter', u'Django Test Query Count ' 227 | u'Documentation', 228 | [u'Ignacio Avas'], 1) 229 | ] 230 | 231 | # If true, show URL addresses after external links. 232 | #man_show_urls = False 233 | 234 | 235 | # -- Options for Texinfo output ------------------------------------------------ 236 | 237 | # Grouping the document tree into Texinfo files. List of tuples 238 | # (source start file, target name, title, author, 239 | # dir menu entry, description, category) 240 | texinfo_documents = [ 241 | ('index', 'django-test-query-counter', u'Django Test Query Count ' 242 | u'Documentation', 243 | u'Ignacio Avas', 'django-test-query-counter', 'One line description of ' 244 | 'project.', 245 | 'Miscellaneous'), 246 | ] 247 | 248 | # Documents to append as an appendix to all manuals. 249 | #texinfo_appendices = [] 250 | 251 | # If false, no module index is generated. 252 | #texinfo_domain_indices = True 253 | 254 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 255 | #texinfo_show_urls = 'footnote' 256 | 257 | # If true, do not generate a @detailmenu in the "Top" node's menu. 258 | #texinfo_no_detailmenu = False 259 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. complexity documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Django Test Query Counter's documentation! 7 | ================================================================= 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authors 19 | history 20 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | At the command line:: 6 | 7 | $ easy_install django-test-query-counter 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv django-test-query-counter 12 | $ pip install django-test-query-counter 13 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Usage 3 | ===== 4 | 5 | To use Django API Query Count in a project, add it to your `INSTALLED_APPS`: 6 | 7 | .. code-block:: python 8 | 9 | INSTALLED_APPS = ( 10 | ... 11 | 'test_query_counter.apps.DjangoApiQueryCountConfig', 12 | ... 13 | ) 14 | 15 | Add Django API Query Count's URL patterns: 16 | 17 | .. code-block:: python 18 | 19 | from test_query_counter import urls as test_query_counter_urls 20 | 21 | 22 | urlpatterns = [ 23 | ... 24 | url(r'^', include(test_query_counter_urls)), 25 | ... 26 | ] 27 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sophilabs/django-test-query-counter/467419b40c6b2cd3f19047522ee25d843b73d768/logo.png -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import unicode_literals, absolute_import 4 | 5 | import os 6 | import sys 7 | 8 | if __name__ == "__main__": 9 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") 10 | from django.core.management import execute_from_command_line 11 | 12 | execute_from_command_line(sys.argv) 13 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Additional requirements go here 2 | Django 3 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | bumpversion==0.5.3 2 | wheel==0.29.0 3 | isort==4.2.15 4 | -------------------------------------------------------------------------------- /requirements_test.txt: -------------------------------------------------------------------------------- 1 | coverage==4.3.4 2 | mock>=1.0.1 3 | flake8>=2.1.0 4 | tox>=1.7.0 5 | codecov>=2.0.0 6 | 7 | 8 | # Additional test requirements go here 9 | -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 3 | from __future__ import unicode_literals, absolute_import 4 | 5 | import os 6 | import sys 7 | 8 | import django 9 | from django.conf import settings 10 | from django.test.utils import get_runner 11 | 12 | 13 | def run_tests(*test_args): 14 | if not test_args: 15 | test_args = ['tests'] 16 | 17 | os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' 18 | django.setup() 19 | TestRunner = get_runner(settings) 20 | test_runner = TestRunner() 21 | failures = test_runner.run_tests(test_args) 22 | sys.exit(bool(failures)) 23 | 24 | 25 | if __name__ == '__main__': 26 | run_tests(*sys.argv[1:]) 27 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.1.0 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | 8 | [bumpversion:file:test_query_counter/__init__.py] 9 | 10 | [wheel] 11 | universal = 1 12 | 13 | [flake8] 14 | ignore = D203 15 | exclude = 16 | test_query_counter/migrations, 17 | .git, 18 | .tox, 19 | docs/conf.py, 20 | build, 21 | dist 22 | max-line-length = 119 23 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import os 4 | import re 5 | import sys 6 | 7 | try: 8 | from setuptools import setup 9 | except ImportError: 10 | from distutils.core import setup 11 | 12 | 13 | def get_version(*file_paths): 14 | """Retrieves the version from test_query_counter/__init__.py""" 15 | filename = os.path.join(os.path.dirname(__file__), *file_paths) 16 | version_file = open(filename).read() 17 | version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", 18 | version_file, re.M) 19 | if version_match: 20 | return version_match.group(1) 21 | raise RuntimeError('Unable to find version string.') 22 | 23 | 24 | version = get_version("test_query_counter", "__init__.py") 25 | 26 | 27 | if sys.argv[-1] == 'publish': 28 | try: 29 | import wheel 30 | print("Wheel version: ", wheel.__version__) # noqa 31 | except ImportError: 32 | print('Wheel library missing. Please run "pip install wheel"') # noqa 33 | sys.exit() 34 | os.system('python setup.py sdist upload') 35 | os.system('python setup.py bdist_wheel upload') 36 | sys.exit() 37 | 38 | if sys.argv[-1] == 'tag': 39 | print("Tagging the version on git:") # noqa 40 | os.system("git tag -a %s -m 'version %s'" % (version, version)) 41 | os.system("git push --tags") 42 | sys.exit() 43 | 44 | readme = open('README.rst').read() 45 | history = open('HISTORY.rst').read().replace('.. :changelog:', '') 46 | 47 | setup( 48 | name='django-test-query-counter', 49 | version=version, 50 | description="""A Django Toolkit for controlling Query count when testing""", 51 | long_description=readme + '\n\n' + history, 52 | author='Ignacio Avas', 53 | author_email='iavas@sophilabs.com', 54 | url='https://github.com/sophilabs/django-request-query-count', 55 | packages=[ 56 | 'test_query_counter', 57 | ], 58 | include_package_data=True, 59 | install_requires=[], 60 | license="MIT", 61 | zip_safe=False, 62 | keywords='django-test-query-counter', 63 | classifiers=[ 64 | 'Development Status :: 3 - Alpha', 65 | 'Framework :: Django', 66 | 'Framework :: Django :: 1.8', 67 | 'Framework :: Django :: 1.9', 68 | 'Framework :: Django :: 1.10', 69 | 'Intended Audience :: Developers', 70 | 'License :: OSI Approved :: BSD License', 71 | 'Natural Language :: English', 72 | 'Programming Language :: Python :: 2', 73 | 'Programming Language :: Python :: 2.7', 74 | 'Programming Language :: Python :: 3', 75 | 'Programming Language :: Python :: 3.3', 76 | 'Programming Language :: Python :: 3.4', 77 | 'Programming Language :: Python :: 3.5', 78 | ], 79 | ) 80 | -------------------------------------------------------------------------------- /test_query_counter/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.1.0' 2 | default_app_config = 'test_query_counter.apps.RequestQueryCountConfig' 3 | -------------------------------------------------------------------------------- /test_query_counter/apps.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 2 | from django.apps import AppConfig 3 | from django.conf import settings 4 | 5 | 6 | class RequestQueryCountConfig(AppConfig): 7 | name = 'test_query_counter' 8 | verbose_name = 'Request Query Count' 9 | 10 | setting_name = 'TEST_QUERY_COUNTER' 11 | 12 | default_settings = { 13 | 'ENABLE': True, 14 | 'ENABLE_STACKTRACES': True, 15 | 'DETAIL_PATH': 'reports/query_count_detail.json', 16 | 'SUMMARY_PATH': 'reports/query_count.json' 17 | } 18 | 19 | @classmethod 20 | def get_setting(cls, setting_name): 21 | return (getattr(settings, cls.setting_name, {}) 22 | .get(setting_name, cls.default_settings[setting_name])) 23 | 24 | @classmethod 25 | def stacktraces_enabled(cls): 26 | return cls.get_setting('ENABLE_STACKTRACES') 27 | 28 | @classmethod 29 | def enabled(cls): 30 | return cls.get_setting('ENABLE') 31 | 32 | def ready(self): 33 | if self.enabled(): 34 | from test_query_counter.manager import RequestQueryCountManager 35 | RequestQueryCountManager.set_up() 36 | -------------------------------------------------------------------------------- /test_query_counter/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sophilabs/django-test-query-counter/467419b40c6b2cd3f19047522ee25d843b73d768/test_query_counter/management/__init__.py -------------------------------------------------------------------------------- /test_query_counter/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sophilabs/django-test-query-counter/467419b40c6b2cd3f19047522ee25d843b73d768/test_query_counter/management/commands/__init__.py -------------------------------------------------------------------------------- /test_query_counter/management/commands/check_query_count.py: -------------------------------------------------------------------------------- 1 | from django.core.management import BaseCommand, CommandError 2 | 3 | from test_query_counter.apps import RequestQueryCountConfig 4 | from test_query_counter.query_count import QueryCountEvaluator 5 | 6 | 7 | class Command(BaseCommand): 8 | 9 | INCREASE_THRESHOLD = 10 # Threshold in percentage 10 | 11 | help = 'Checks if the API query_count has increased since the last run. ' \ 12 | 'Query count is measured per test case, and per API call.' 13 | 14 | CURRENT_QUERY_COUNT = 'reports/query_count.json' 15 | 16 | def add_arguments(self, parser): 17 | super().add_arguments(parser) 18 | parser.add_argument('--last-count-file', 19 | dest='last_count_file', 20 | help='JSON summary file to compare against.', 21 | required=True) 22 | 23 | summary_path = RequestQueryCountConfig.get_setting('SUMMARY_PATH') 24 | parser.add_argument('--query-count-file', 25 | dest='query_count_file', 26 | help='JSON summary file for current run.', 27 | default=summary_path) 28 | 29 | help_msg = 'Threshold tolerance, which is computed in percentage. ' \ 30 | 'Defaults to {}%%'.format(self.INCREASE_THRESHOLD) 31 | parser.add_argument('--query-count-threhold', 32 | dest='query_count_threshold', 33 | type=float, default=self.INCREASE_THRESHOLD, 34 | help=help_msg) 35 | 36 | def handle(self, *args, **options): 37 | with open(options['query_count_file']) as current_file, \ 38 | open(options['last_count_file']) as last_file: 39 | violations = QueryCountEvaluator(options['query_count_threshold'], 40 | current_file, last_file).run() 41 | 42 | if violations: 43 | raise CommandError('There was at least one test with an API ' 44 | 'call excedding the allowed threshold.') 45 | -------------------------------------------------------------------------------- /test_query_counter/manager.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 2 | import inspect 3 | import json 4 | import os 5 | import os.path 6 | import threading 7 | 8 | from django.conf import settings 9 | from django.test import SimpleTestCase 10 | from django.test.utils import get_runner 11 | from django.utils.module_loading import import_string 12 | from test_query_counter.apps import RequestQueryCountConfig 13 | from test_query_counter.query_count import (TestCaseQueryContainer, 14 | TestResultQueryContainer) 15 | 16 | local = threading.local() 17 | 18 | 19 | class RequestQueryCountManager(object): 20 | LOCAL_TESTCASE_CONTAINER_NAME = 'querycount_test_case_container' 21 | queries = None 22 | 23 | @classmethod 24 | def get_testcase_container(cls): 25 | return getattr(local, cls.LOCAL_TESTCASE_CONTAINER_NAME, None) 26 | 27 | @classmethod 28 | def is_middleware_class(cls, middleware_path): 29 | from test_query_counter.middleware import Middleware 30 | 31 | try: 32 | middleware_cls = import_string(middleware_path) 33 | except ImportError: 34 | return 35 | return ( 36 | inspect.isclass(middleware_cls) and 37 | issubclass(middleware_cls, Middleware) 38 | ) 39 | 40 | @classmethod 41 | def add_middleware(cls): 42 | middleware_class_name = 'test_query_counter.middleware.Middleware' 43 | middleware_setting = getattr(settings, 'MIDDLEWARE', None) 44 | setting_name = 'MIDDLEWARE' 45 | if middleware_setting is None: 46 | middleware_setting = settings.MIDDLEWARE_CLASSES 47 | setting_name = 'MIDDLEWARE_CLASSES' 48 | 49 | # add the middleware only if it was not added before 50 | if not any(map(cls.is_middleware_class, middleware_setting)): 51 | if isinstance(middleware_setting, list): 52 | new_middleware_setting = ( 53 | middleware_setting + 54 | [middleware_class_name] 55 | ) 56 | elif isinstance(middleware_setting, tuple): 57 | new_middleware_setting = ( 58 | middleware_setting + 59 | (middleware_class_name,) 60 | ) 61 | else: 62 | err_msg = "{} is missing from {}.".format( 63 | middleware_class_name, 64 | setting_name 65 | ) 66 | raise TypeError(err_msg) 67 | 68 | setattr(settings, setting_name, new_middleware_setting) 69 | 70 | @classmethod 71 | def wrap_pre_set_up(cls, set_up): 72 | def wrapped(self, *args, **kwargs): 73 | result = set_up(self, *args, **kwargs) 74 | if RequestQueryCountConfig.enabled(): 75 | setattr(local, cls.LOCAL_TESTCASE_CONTAINER_NAME, 76 | TestCaseQueryContainer()) 77 | return result 78 | 79 | return wrapped 80 | 81 | @classmethod 82 | def wrap_post_tear_down(cls, tear_down): 83 | def wrapped(self, *args, **kwargs): 84 | if (not hasattr(cls, 'queries') or not 85 | RequestQueryCountConfig.enabled()): 86 | return tear_down(self, *args, **kwargs) 87 | 88 | container = cls.get_testcase_container() 89 | 90 | test_method = getattr(self, self._testMethodName) 91 | 92 | exclusions = ( 93 | getattr(self.__class__, "__querycount_exclude__", []) + 94 | getattr(test_method, "__querycount_exclude__", []) 95 | ) 96 | 97 | all_queries = cls.queries 98 | current_queries = container.filter_by(exclusions) 99 | all_queries.add(self.id(), current_queries) 100 | 101 | return tear_down(self, *args, **kwargs) 102 | 103 | return wrapped 104 | 105 | @classmethod 106 | def patch_test_case(cls): 107 | SimpleTestCase._pre_setup = cls.wrap_pre_set_up( 108 | SimpleTestCase._pre_setup 109 | ) 110 | SimpleTestCase._post_teardown = cls.wrap_post_tear_down( 111 | SimpleTestCase._post_teardown 112 | ) 113 | 114 | @classmethod 115 | def save_json(cls, setting_name, container, detail): 116 | summary_path = os.path.realpath(RequestQueryCountConfig.get_setting( 117 | setting_name)) 118 | os.makedirs(os.path.dirname(summary_path), exist_ok=True) 119 | 120 | with open(summary_path, 'w') as json_file: 121 | json.dump(container.get_json(detail=detail), json_file, 122 | ensure_ascii=False, indent=4, sort_keys=True) 123 | 124 | @classmethod 125 | def wrap_setup_test_environment(cls, func): 126 | def wrapped(self, *args, **kwargs): 127 | result = func(self, *args, **kwargs) 128 | if not RequestQueryCountConfig.enabled(): 129 | return result 130 | cls.queries = TestResultQueryContainer() 131 | return result 132 | 133 | return wrapped 134 | 135 | @classmethod 136 | def wrap_teardown_test_environment(cls, func): 137 | def wrapped(self, *args, **kwargs): 138 | result = func(self, *args, **kwargs) 139 | if not RequestQueryCountConfig.enabled(): 140 | return result 141 | cls.save_json('SUMMARY_PATH', cls.queries, False) 142 | cls.save_json('DETAIL_PATH', cls.queries, True) 143 | cls.queries = None 144 | return result 145 | 146 | return wrapped 147 | 148 | @classmethod 149 | def patch_runner(cls): 150 | # FIXME: this is incompatible with --parallel and --test-runner 151 | # command arguments 152 | test_runner = get_runner(settings) 153 | 154 | if (not hasattr(test_runner, 'setup_test_environment') or not 155 | hasattr(test_runner, 'teardown_test_environment')): 156 | return 157 | 158 | test_runner.setup_test_environment = cls.wrap_setup_test_environment( 159 | test_runner.setup_test_environment 160 | ) 161 | test_runner.teardown_test_environment = \ 162 | cls.wrap_teardown_test_environment( 163 | test_runner.teardown_test_environment 164 | ) 165 | 166 | @classmethod 167 | def set_up(cls): 168 | cls.add_middleware() 169 | cls.patch_test_case() 170 | cls.patch_runner() 171 | -------------------------------------------------------------------------------- /test_query_counter/middleware.py: -------------------------------------------------------------------------------- 1 | from django.core.exceptions import MiddlewareNotUsed 2 | from django.core.signals import request_started 3 | from django.db import DEFAULT_DB_ALIAS, connections, reset_queries 4 | from test_query_counter.apps import RequestQueryCountConfig 5 | from test_query_counter.manager import RequestQueryCountManager 6 | 7 | try: 8 | from django.utils.deprecation import MiddlewareMixin 9 | except ImportError: # Django < 1.10 10 | # Works perfectly for everyone using MIDDLEWARE_CLASSES 11 | MiddlewareMixin = object 12 | 13 | 14 | class Middleware(MiddlewareMixin): 15 | """ 16 | Intercepts queries in a request and put it in the query container provided 17 | by the RequestQueryCountConfig, during the wrapped test setUp method. 18 | 19 | The middleware is intended to be automatically added 20 | 21 | If the query container is None, then the middleware is not executed. 22 | """ 23 | 24 | def __init__(self, *args, **kwargs): 25 | super().__init__(*args, **kwargs) 26 | if not RequestQueryCountConfig.enabled(): 27 | raise MiddlewareNotUsed() 28 | self.force_debug_cursor = False 29 | self.initial_queries = 0 30 | self.final_queries = None 31 | self.connection = connections[DEFAULT_DB_ALIAS] 32 | 33 | def process_request(self, _): 34 | if RequestQueryCountManager.get_testcase_container(): 35 | # Took from django.test.utils.CaptureQueriesContext 36 | self.force_debug_cursor = self.connection.force_debug_cursor 37 | self.connection.force_debug_cursor = True 38 | self.initial_queries = len(self.connection.queries_log) 39 | self.final_queries = None 40 | request_started.disconnect(reset_queries) 41 | 42 | def process_response(self, request, response): 43 | if RequestQueryCountManager.get_testcase_container(): 44 | # Took from django.test.utils.CaptureQueriesContext 45 | self.connection.force_debug_cursor = self.force_debug_cursor 46 | request_started.connect(reset_queries) 47 | final_queries = len(self.connection.queries_log) 48 | captured_queries = self.connection.queries[ 49 | self.initial_queries:final_queries 50 | ] 51 | 52 | query_container = RequestQueryCountManager.get_testcase_container() 53 | query_container.add(request, captured_queries) 54 | 55 | return response 56 | -------------------------------------------------------------------------------- /test_query_counter/models.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sophilabs/django-test-query-counter/467419b40c6b2cd3f19047522ee25d843b73d768/test_query_counter/models.py -------------------------------------------------------------------------------- /test_query_counter/query_count.py: -------------------------------------------------------------------------------- 1 | import json 2 | import re 3 | import sys 4 | from sys import maxsize, stderr 5 | 6 | ANY = '' 7 | 8 | 9 | class QueryCountExclusion(object): 10 | """Represents an test condition to exclude some of the query counts made 11 | by the requests. Meant to be used in exclude_query_count""" 12 | 13 | def __init__(self, path, method, count): 14 | self.path = re.compile(path, re.IGNORECASE) 15 | self.method = re.compile(method, re.IGNORECASE) 16 | self.count = count 17 | 18 | def is_excluded(self, method, path, queries): 19 | """ 20 | Compare method path against the exclusion 21 | 22 | :param method: method to compare against 23 | :param path: path to compare 24 | :param queries: number of queries made to that particular request 25 | :return: True if this exclusion applies to the request 26 | """ 27 | return self.method.search(method) and self.path.search(path) \ 28 | and len(queries) <= self.count 29 | 30 | 31 | def exclude_query_count(path=ANY, method=ANY, count=sys.maxsize): 32 | """ 33 | Conditionally exclude a query count path, by path, method and count 34 | 35 | :param path: the or regex of the excluded path(s). 36 | :param method: the regex of the method(s) to exclude. 37 | :param count: minimum number of queries tolerated. 38 | Requests with less or same amount as "count" will be excluded. 39 | """ 40 | 41 | def decorator(test_item): 42 | exclude_list = getattr(test_item, '__querycount_exclude__', []) 43 | exclude_list.append(QueryCountExclusion(path, method, count)) 44 | test_item.__querycount_exclude__ = exclude_list 45 | return test_item 46 | 47 | return decorator 48 | 49 | 50 | class TestResultQueryContainer(object): 51 | """Stores all the queries from a Test Run, aggregated by Test Case""" 52 | 53 | def __init__(self): 54 | self.queries_by_testcase = dict() 55 | self.total = 0 56 | 57 | def add(self, test_case_id, queries): 58 | """ 59 | Merge the queries from a test case 60 | :param test_case_id: identifier for test case (This is usually the 61 | full name of the test method, including the module and class name) 62 | :param queries: TestCaseQueries for this test case 63 | """ 64 | existing_query_container = self.queries_by_testcase.get( 65 | test_case_id, 66 | TestCaseQueryContainer() 67 | ) 68 | existing_query_container.merge(queries) 69 | self.queries_by_testcase[test_case_id] = existing_query_container 70 | self.total += existing_query_container.total 71 | 72 | @classmethod 73 | def test_case_json(cls, test_case_id, query_container, detail): 74 | """Returns a JSON compatible representation of the test case queries""" 75 | representation = query_container.get_json(detail) 76 | representation['id'] = test_case_id 77 | return representation 78 | 79 | def get_json(self, detail): 80 | """ 81 | Returns a JSON compatible representation of the Test Result. Contains 82 | all queries ran in the test case 83 | 84 | :param detail: If True, will include query details 85 | """ 86 | return { 87 | 'total': self.total, 88 | 'test_cases': [ 89 | self.test_case_json(test_case_id, queries, detail) 90 | for test_case_id, queries in self.queries_by_testcase.items() 91 | ] 92 | } 93 | 94 | 95 | class TestCaseQueryContainer(object): 96 | """Stores queries by API method for a particular test case""" 97 | def __init__(self, queries_by_api_method=None): 98 | self.recorded_requests = set() 99 | self.queries_by_api_method = queries_by_api_method or dict() 100 | self.total = len(self.queries_by_api_method) 101 | 102 | def add_by_key(self, api_method_key, queries): 103 | """ 104 | Appends queries to a certain api method 105 | :param api_method_key: tuple (method, path) 106 | :param queries: list of queries 107 | """ 108 | existing_queries = self.queries_by_api_method.get(api_method_key, []) 109 | self.queries_by_api_method[api_method_key] = queries + existing_queries 110 | self.total += len(queries) 111 | 112 | def add(self, request, queries): 113 | """Agregates the queries to the captured queries dict""" 114 | if request in self.recorded_requests: 115 | return 116 | 117 | self.recorded_requests.add(request) 118 | key = (request.method, request.path) 119 | self.add_by_key(key, queries) 120 | 121 | def merge(self, test_case_container): 122 | """ 123 | Merges the queries from another test case container in this object 124 | :param test_case_container: an existing test Container 125 | """ 126 | for key, queries in test_case_container.queries_by_api_method.items(): 127 | self.add_by_key(key, queries) 128 | 129 | @classmethod 130 | def excluded(cls, method, path, queries, exclusion_list): 131 | return any(( 132 | exclusion.is_excluded(method, path, queries) 133 | for exclusion in exclusion_list 134 | )) 135 | 136 | def filter_by(self, exclusion_list): 137 | return TestCaseQueryContainer({ 138 | (method, path): queries 139 | for (method, path), queries in self.queries_by_api_method.items() 140 | if not self.excluded(method, path, queries, exclusion_list) 141 | }) 142 | 143 | @classmethod 144 | def api_call_json(cls, api_call, queries, detail): 145 | """ 146 | Returns a json representation of a single API Call 147 | :param api_call: API call tuple (method, path) 148 | :param queries: list of queries 149 | :param detail: if True, the list of queries is returned 150 | :return: Dictionary 151 | """ 152 | method, path = api_call 153 | result = { 154 | 'method': method, 155 | 'path': path, 156 | 'total': len(queries), 157 | } 158 | if detail: 159 | result['queries'] = queries 160 | return result 161 | 162 | def get_json(self, detail): 163 | """Returns a JSON representation of the object""" 164 | return { 165 | 'total': self.total, 166 | 'queries': [ 167 | self.api_call_json(api_call, queries, detail) 168 | for api_call, queries in self.queries_by_api_method.items() 169 | ] 170 | } 171 | 172 | 173 | class Violation(object): 174 | 175 | def __init__(self, test_case_id, method, path, threshold, total): 176 | self.test_case_id = test_case_id 177 | self.method = method 178 | self.path = path 179 | self.threshold = threshold 180 | self.total = total 181 | 182 | 183 | class QueryCountEvaluator(object): 184 | 185 | def __init__(self, threshold, current_file, last_file, stream=stderr): 186 | """ 187 | Initializes the Evaluator, which writes t 188 | :param threshold: Threshold in percentage (e.g. 10) 189 | :param current_file: stream with the about-to-commit API Calls result 190 | :param last_file: stream with the last "accepted" API calls to compare 191 | :param stream: steam to write into (default: stderr) 192 | """ 193 | self.threshold = threshold 194 | self.current = json.load(current_file) 195 | self.last = json.load(last_file) 196 | self.stream = stream 197 | 198 | @classmethod 199 | def default_test_case_element(cls, test_case_id): 200 | return { 201 | 'id': test_case_id, 202 | 'queries': [], 203 | 'total': 0 204 | } 205 | 206 | def list_violations(self): 207 | last_test_cases = { 208 | test_case['id']: test_case 209 | for test_case in self.last['test_cases'] 210 | } 211 | 212 | for element in self.current['test_cases']: 213 | test_case_id = element['id'] 214 | last_test_cases_queries = last_test_cases.get( 215 | test_case_id, 216 | self.default_test_case_element(test_case_id) 217 | ) 218 | for violation in self.compare_test_cases( 219 | test_case_id, 220 | element['queries'], 221 | last_test_cases_queries['queries']): 222 | yield violation 223 | 224 | def run(self): 225 | """ 226 | Main method. Compares to JSON files and prints in the stream the 227 | list of API Calls (Violations) that ocurred between the current run 228 | and the last run. 229 | :return: a list of the violations ocurred 230 | """ 231 | violations = list(self.list_violations()) 232 | if any(violations): 233 | self.stream.write('There are test cases with API ' 234 | 'calls that exceeded threshold:\n\n') 235 | 236 | for violation in violations: 237 | msg = '\tIn test case {}, {} {}. Expected at most {} queries but' \ 238 | ' got {} queries' \ 239 | '\n'.format(violation.test_case_id, violation.method, 240 | violation.path, violation.threshold, 241 | violation.total) 242 | self.stream.write(msg) 243 | 244 | if not any(violations): 245 | self.stream.write('All Tests API Queries are below the allowed ' 246 | 'threshold.\n') 247 | 248 | self.stream.flush() 249 | 250 | return violations 251 | 252 | def compare_test_cases(self, test_case_id, current_queries, last_queries): 253 | """ 254 | Compares the queries from a test case 255 | :param test_case_id: the name of the test case. Usually includes the 256 | class and the method name 257 | :param current_queries: API calls query list for the current run 258 | :param last_queries: API calls query for the last run 259 | :return: a list of Violation objects for any API Call that exceeded 260 | threshold 261 | """ 262 | last_queries_dict = { 263 | (element['method'], element['path']): element['total'] 264 | for element in last_queries 265 | } 266 | 267 | def get_last_queries(query_element): 268 | key = (query_element['method'], query_element['path']) 269 | return last_queries_dict.get(key, maxsize) 270 | 271 | def get_threshold(query_element): 272 | max_factor = (self.threshold / 100.0 + 1) 273 | return round(get_last_queries(query_element) * max_factor) 274 | 275 | def violates_threshold(query_element): 276 | return query_element['total'] > get_threshold(query_element) 277 | 278 | return (Violation(test_case_id, element['method'], element['path'], 279 | get_threshold(element), element['total']) 280 | for element in current_queries 281 | if violates_threshold(element)) 282 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sophilabs/django-test-query-counter/467419b40c6b2cd3f19047522ee25d843b73d768/tests/__init__.py -------------------------------------------------------------------------------- /tests/settings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 2 | from __future__ import absolute_import, unicode_literals 3 | 4 | import os.path 5 | from tempfile import mkdtemp 6 | 7 | import django 8 | 9 | DEBUG = True 10 | USE_TZ = True 11 | 12 | # SECURITY WARNING: keep the secret key used in production secret! 13 | SECRET_KEY = '66666666666666666666666666666666666666666666666666' 14 | 15 | DATABASES = { 16 | 'default': { 17 | 'ENGINE': 'django.db.backends.sqlite3', 18 | 'NAME': ':memory:', 19 | } 20 | } 21 | 22 | tempdir = mkdtemp('test_query_counter_tests') 23 | 24 | TEST_QUERY_COUNTER = { 25 | 'ENABLE': True, 26 | 'DETAIL_PATH': os.path.join(tempdir, 'query_count_detail.json'), 27 | 'SUMMARY_PATH': os.path.join(tempdir, 'query_count.json') 28 | } 29 | 30 | ROOT_URLCONF = 'tests.urls' 31 | 32 | INSTALLED_APPS = [ 33 | 'django_jenkins', 34 | 'django.contrib.auth', 35 | 'django.contrib.contenttypes', 36 | 'django.contrib.sites', 37 | 'django', 38 | 'test_query_counter', 39 | ] 40 | 41 | SITE_ID = 1 42 | 43 | if django.VERSION >= (1, 10): 44 | MIDDLEWARE = () 45 | else: 46 | MIDDLEWARE_CLASSES = () 47 | -------------------------------------------------------------------------------- /tests/test_app_config.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.test import TestCase, override_settings 3 | from test_query_counter.apps import RequestQueryCountConfig 4 | from test_query_counter.manager import RequestQueryCountManager 5 | 6 | 7 | class TestAppConfig(TestCase): 8 | 9 | def test_default_enabled(self): 10 | self.assertTrue(RequestQueryCountConfig.enabled()) 11 | 12 | @override_settings(TEST_QUERY_COUNTER={'ENABLE': False}) 13 | def test_override_disabled(self): 14 | self.assertFalse(RequestQueryCountConfig.enabled()) 15 | 16 | @override_settings(TEST_QUERY_COUNTER={'ENABLE': True}) 17 | def test_override_enabled(self): 18 | self.assertTrue(RequestQueryCountConfig.enabled()) 19 | 20 | def test_add_middleware_twice(self): 21 | RequestQueryCountManager.add_middleware() 22 | RequestQueryCountManager.add_middleware() 23 | 24 | middlewares = settings.MIDDLEWARE 25 | self.assertEqual(len(middlewares), 1) 26 | self.assertEqual(middlewares[0], 27 | 'test_query_counter.middleware.Middleware' 28 | ) 29 | 30 | def test_list_middlewares_types(self): 31 | with override_settings(MIDDLEWARE=[]): 32 | RequestQueryCountManager.add_middleware() 33 | self.assertEqual(settings.MIDDLEWARE, [ 34 | 'test_query_counter.middleware.Middleware' 35 | ]) 36 | with override_settings(MIDDLEWARE=()): 37 | RequestQueryCountManager.add_middleware() 38 | self.assertEqual( 39 | settings.MIDDLEWARE, 40 | ('test_query_counter.middleware.Middleware',) 41 | ) 42 | with override_settings(MIDDLEWARE='some_nasty_thing'): 43 | with self.assertRaises(Exception): 44 | RequestQueryCountManager.add_middleware() 45 | -------------------------------------------------------------------------------- /tests/test_middleware.py: -------------------------------------------------------------------------------- 1 | import os 2 | from io import StringIO 3 | from os import path 4 | from unittest import TestLoader, TextTestRunner, mock 5 | from unittest.mock import MagicMock 6 | 7 | from django.core.exceptions import MiddlewareNotUsed 8 | from django.test import TestCase, override_settings 9 | from django.test.runner import DiscoverRunner 10 | from test_query_counter.apps import RequestQueryCountConfig 11 | from test_query_counter.manager import RequestQueryCountManager 12 | from test_query_counter.middleware import Middleware 13 | 14 | 15 | class TestMiddleWare(TestCase): 16 | 17 | def setUp(self): 18 | # Simple class that doesn't output to the standard output 19 | class StringIOTextRunner(TextTestRunner): 20 | def __init__(self, *args, **kwargs): 21 | kwargs['stream'] = StringIO() 22 | super().__init__(*args, **kwargs) 23 | 24 | self.test_runner = DiscoverRunner() 25 | self.test_runner.test_runner = StringIOTextRunner 26 | 27 | def tearDown(self): 28 | try: 29 | os.remove(RequestQueryCountConfig.get_setting('DETAIL_PATH')) 30 | except FileNotFoundError: 31 | pass 32 | try: 33 | os.remove(RequestQueryCountConfig.get_setting('SUMMARY_PATH')) 34 | except FileNotFoundError: 35 | pass 36 | 37 | def test_middleware_called(self): 38 | with mock.patch('test_query_counter.middleware.Middleware', 39 | new=MagicMock(wraps=Middleware)) as mocked: 40 | self.client.get('/url-1') 41 | self.assertEqual(mocked.call_count, 1) 42 | 43 | def test_case_injected_one_test(self): 44 | class Test(TestCase): 45 | def test_foo(self): 46 | self.client.get('/url-1') 47 | 48 | self.test_runner.setup_test_environment() 49 | self.test_runner.run_suite(TestLoader().loadTestsFromTestCase( 50 | testCaseClass=Test)) 51 | self.test_runner.teardown_test_environment() 52 | 53 | self.assertEqual(RequestQueryCountManager.queries.total, 1) 54 | 55 | def test_case_injected_two_tests(self): 56 | class Test(TestCase): 57 | def test_foo(self): 58 | self.client.get('/url-1') 59 | 60 | def test_bar(self): 61 | self.client.get('/url-2') 62 | 63 | self.test_runner.run_suite( 64 | TestLoader().loadTestsFromTestCase(testCaseClass=Test) 65 | ) 66 | 67 | self.assertEqual(RequestQueryCountManager.queries.total, 2) 68 | 69 | @override_settings(TEST_QUERY_COUNTER={'ENABLE': False}) 70 | def test_case_disable_setting(self): 71 | class Test(TestCase): 72 | def test_foo(self): 73 | self.client.get('/url-1') 74 | 75 | def test_bar(self): 76 | self.client.get('/url-2') 77 | 78 | self.test_runner.run_tests( 79 | None, 80 | TestLoader().loadTestsFromTestCase(testCaseClass=Test) 81 | ) 82 | self.assertIsNone(RequestQueryCountManager.queries) 83 | 84 | @override_settings(TEST_QUERY_COUNTER={'ENABLE': False}) 85 | def test_disabled(self): 86 | mock_get_response = object() 87 | with self.assertRaises(MiddlewareNotUsed): 88 | Middleware(mock_get_response) 89 | 90 | def test_json_exists(self): 91 | class Test(TestCase): 92 | def test_foo(self): 93 | self.client.get('/url-1') 94 | 95 | self.assertFalse(path.exists( 96 | RequestQueryCountConfig.get_setting('DETAIL_PATH')) 97 | ) 98 | self.test_runner.run_tests( 99 | None, 100 | TestLoader().loadTestsFromTestCase(testCaseClass=Test) 101 | ) 102 | self.assertTrue(path.exists( 103 | RequestQueryCountConfig.get_setting('DETAIL_PATH')) 104 | ) 105 | -------------------------------------------------------------------------------- /tests/test_query_count_containers.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | from test_query_counter.query_count import (TestCaseQueryContainer, 4 | TestResultQueryContainer) 5 | 6 | 7 | class MockRequest(object): 8 | 9 | def __init__(self, method, path): 10 | self.method = method 11 | self.path = path 12 | 13 | 14 | class QueryCountContainersTestCase(TestCase): 15 | 16 | def test_case_add(self): 17 | container = TestCaseQueryContainer() 18 | self.assertEqual(container.total, 0) 19 | 20 | container.add( 21 | MockRequest('get', 'request_path'), 22 | [ 23 | {'sql': 'SELECT * FROM some_table', 'time': 0.02}, 24 | {'sql': 'SELECT * FROM some_other_table', 'time': 0.01} 25 | ] 26 | ) 27 | self.assertEqual(container.total, 2) 28 | 29 | container.add( 30 | MockRequest('post', 'request_path'), 31 | [ 32 | {'sql': 'SELECT * FROM some_table_3', 'time': 0.02}, 33 | ] 34 | ) 35 | self.assertEqual(container.total, 3) 36 | 37 | def test_case_empty_json(self): 38 | self.assertEqual(TestCaseQueryContainer().get_json(False), { 39 | 'total': 0, 40 | 'queries': [] 41 | }) 42 | 43 | def test_case_non_empty_json(self): 44 | container = TestCaseQueryContainer() 45 | container.add( 46 | MockRequest('options', 'request_path'), 47 | [ 48 | {'sql': 'SELECT * FROM some_table', 'time': 0.02}, 49 | ] 50 | ) 51 | 52 | self.assertEqual(container.get_json(detail=False), { 53 | 'total': 1, 54 | 'queries': [ 55 | { 56 | 'method': 'options', 57 | 'path': 'request_path', 58 | 'total': 1 59 | } 60 | ] 61 | }) 62 | 63 | self.assertEqual(container.get_json(detail=True), { 64 | 'total': 1, 65 | 'queries': [ 66 | { 67 | 'method': 'options', 68 | 'path': 'request_path', 69 | 'total': 1, 70 | 'queries': [ 71 | {'sql': 'SELECT * FROM some_table', 'time': 0.02} 72 | ] 73 | } 74 | ] 75 | }) 76 | 77 | def test_case_merge(self): 78 | container = TestCaseQueryContainer() 79 | container.add( 80 | MockRequest('delete', 'request_path'), 81 | [ 82 | {'sql': 'SELECT * FROM some_table', 'time': 0.02}, 83 | ] 84 | ) 85 | container_2 = TestCaseQueryContainer() 86 | container_2.add( 87 | MockRequest('delete', 'request_path'), 88 | [ 89 | {'sql': 'SELECT * FROM some_othertable', 'time': 0.05}, 90 | ] 91 | ) 92 | 93 | container.merge(container_2) 94 | self.assertEqual(container.total, 2) 95 | self.assertEqual( 96 | len(container.queries_by_api_method.keys()), 97 | 1 98 | ) 99 | 100 | def test_result_empty(self): 101 | container = TestResultQueryContainer() 102 | self.assertEqual(container.total, 0) 103 | 104 | def test_result_add(self): 105 | result_container = TestResultQueryContainer() 106 | test_case_container = TestCaseQueryContainer() 107 | test_case_container.add( 108 | MockRequest('delete', 'some_path'), 109 | [ 110 | {'sql': 'SELECT * FROM a_table', 'time': 0.02}, 111 | ] 112 | ) 113 | result_container.add('some.test.test_function', test_case_container) 114 | self.assertEqual(result_container.total, 1) 115 | 116 | test_case_container = TestCaseQueryContainer() 117 | test_case_container.add( 118 | MockRequest('patch', 'other_path'), 119 | [ 120 | {'sql': 'SELECT * FROM a_table', 'time': 0.02}, 121 | ] 122 | ) 123 | result_container.add('some.test.test_other', test_case_container) 124 | self.assertEqual(result_container.total, 2) 125 | 126 | def test_result_empty_json(self): 127 | container = TestResultQueryContainer() 128 | self.assertEqual(container.get_json(detail=True), { 129 | 'total': 0, 130 | 'test_cases': [] 131 | }) 132 | 133 | def test_result_single_json(self): 134 | result_container = TestResultQueryContainer() 135 | test_case_container = TestCaseQueryContainer() 136 | test_case_container.add( 137 | MockRequest('delete', 'some_path'), 138 | [ 139 | {'sql': 'SELECT * FROM a_table', 'time': 0.02}, 140 | ] 141 | ) 142 | result_container.add('some.test.test_function', test_case_container) 143 | 144 | json_obj = result_container.get_json(detail=False) 145 | 146 | self.assertEqual(json_obj['total'], 1) 147 | self.assertEqual(len(json_obj['test_cases']), 1) 148 | self.assertEqual( 149 | json_obj['test_cases'][0]['id'], 150 | 'some.test.test_function' 151 | ) 152 | -------------------------------------------------------------------------------- /tests/test_query_count_evaluator.py: -------------------------------------------------------------------------------- 1 | import json 2 | import re 3 | from io import StringIO 4 | 5 | from django.test import TestCase 6 | 7 | from test_query_counter.query_count import QueryCountEvaluator 8 | 9 | 10 | class TestQueryCountEvaluator(TestCase): 11 | 12 | @staticmethod 13 | def make(test_cases): 14 | return StringIO(json.dumps({ 15 | 'test_cases': test_cases, 16 | 'total': 0 17 | })) 18 | 19 | def setUp(self): 20 | self.evaluator = QueryCountEvaluator(10, self.make([]), self.make([]), 21 | StringIO()) 22 | 23 | def test_empty(self): 24 | violations = self.evaluator.compare_test_cases('test-case-id', [], []) 25 | self.assertFalse(any(violations)) 26 | 27 | def test_new_api_call(self): 28 | violations = self.evaluator.compare_test_cases( 29 | 'test-case-id', 30 | [ 31 | { 32 | "method": "post", 33 | "path": "/api/events", 34 | "total": 45 35 | } 36 | ], 37 | [] 38 | ) 39 | self.assertFalse(any(violations)) 40 | 41 | def test_api_call_removed(self): 42 | violations = self.evaluator.compare_test_cases( 43 | 'test-case-id', 44 | [], 45 | [ 46 | { 47 | "method": "post", 48 | "path": "/api/events", 49 | "total": 45 50 | } 51 | ], 52 | ) 53 | self.assertFalse(any(violations)) 54 | 55 | def test_api_below_threshold_limit(self): 56 | violations = self.evaluator.compare_test_cases( 57 | 'test-case-id', 58 | [ 59 | { 60 | "method": "post", 61 | "path": "/api/events", 62 | "total": 90 63 | } 64 | ], 65 | [ 66 | { 67 | "method": "post", 68 | "path": "/api/events", 69 | "total": 100 70 | } 71 | ] 72 | ) 73 | self.assertFalse(any(violations)) 74 | 75 | def test_on_threshold_limit(self): 76 | violations = self.evaluator.compare_test_cases( 77 | 'test-case-id', 78 | [ 79 | { 80 | "method": "post", 81 | "path": "/api/events", 82 | "total": 110 83 | } 84 | ], 85 | [ 86 | { 87 | "method": "post", 88 | "path": "/api/events", 89 | "total": 100 90 | } 91 | ] 92 | ) 93 | self.assertFalse(any(violations)) 94 | 95 | def test_above_threshold_limit(self): 96 | violations = self.evaluator.compare_test_cases( 97 | 'test-case-id', 98 | [ 99 | { 100 | "method": "post", 101 | "path": "/api/events", 102 | "total": 120 103 | } 104 | ], 105 | [ 106 | { 107 | "method": "post", 108 | "path": "/api/events", 109 | "total": 100 110 | } 111 | ] 112 | ) 113 | violation = next(violations) 114 | 115 | self.assertEqual(violation.test_case_id, 'test-case-id') 116 | self.assertEqual(violation.method, 'post') 117 | self.assertEqual(violation.path, '/api/events') 118 | self.assertEqual(violation.threshold, 110) 119 | self.assertEqual(violation.total, 120) 120 | 121 | def test_one_above_one_below(self): 122 | violations = list(self.evaluator.compare_test_cases( 123 | 'test-case-id', 124 | [ 125 | { 126 | "method": "post", 127 | "path": "/api/events", 128 | "total": 100 129 | }, 130 | { 131 | "method": "get", 132 | "path": "/api/events", 133 | "total": 120 134 | } 135 | ], 136 | [ 137 | { 138 | "method": "post", 139 | "path": "/api/events", 140 | "total": 100 141 | }, 142 | { 143 | "method": "get", 144 | "path": "/api/events", 145 | "total": 100 146 | } 147 | ] 148 | )) 149 | 150 | self.assertEqual(len(violations), 1) 151 | self.assertEqual(violations[0].method, 'get') 152 | 153 | def test_run_wo_violations(self): 154 | violations = self.evaluator.run() 155 | self.assertEqual(len(violations), 0) 156 | self.assertIsNotNone( 157 | re.search('All Tests API Queries are below the allowed', 158 | self.evaluator.stream.getvalue())) 159 | 160 | def test_run_w_violations(self): 161 | evaluator = QueryCountEvaluator( 162 | 10, 163 | self.make([ 164 | { 165 | "id": "test-case-1", 166 | "queries": [ 167 | { 168 | "method": "post", 169 | "path": "path/1", 170 | "total": 120 171 | } 172 | ], 173 | "total": 120 174 | }, 175 | { 176 | "id": "test-case-2", 177 | "queries": [ 178 | { 179 | "method": "get", 180 | "path": "path/2", 181 | "total": 60 182 | } 183 | ], 184 | "total": 60 185 | }, 186 | { 187 | "id": "test-3", 188 | "queries": [ 189 | { 190 | "method": "put", 191 | "path": "path/3", 192 | "total": 5 193 | } 194 | ], 195 | "total": 5 196 | } 197 | ]), 198 | self.make([ 199 | { 200 | "id": "test-case-1", 201 | "queries": [ 202 | { 203 | "method": "post", 204 | "path": "path/1", 205 | "total": 100 206 | } 207 | ], 208 | "total": 100 209 | }, 210 | { 211 | "id": "test-case-2", 212 | "queries": [ 213 | { 214 | "method": "get", 215 | "path": "path/2", 216 | "total": 50 217 | } 218 | ], 219 | "total": 50 220 | }, 221 | { 222 | "id": "test-3", 223 | "queries": [ 224 | { 225 | "method": "put", 226 | "path": "path/3", 227 | "total": 5 228 | } 229 | ], 230 | "total": 5 231 | } 232 | ]), 233 | StringIO() 234 | ) 235 | 236 | violations = evaluator.run() 237 | self.assertEqual(len(violations), 2) 238 | self.assertIsNotNone( 239 | re.search(r'calls that exceeded threshold', 240 | evaluator.stream.getvalue()) 241 | ) 242 | self.assertIsNotNone( 243 | re.search(r'In test case test-case-1', 244 | evaluator.stream.getvalue()) 245 | ) 246 | self.assertIsNotNone( 247 | re.search(r'In test case test-case-2', 248 | evaluator.stream.getvalue()) 249 | ) 250 | self.assertIsNone( 251 | re.search(r'In test case test-3', 252 | evaluator.stream.getvalue()) 253 | ) 254 | -------------------------------------------------------------------------------- /tests/test_query_count_runner.py: -------------------------------------------------------------------------------- 1 | import os 2 | from io import StringIO 3 | from os import path 4 | from unittest import TestLoader, TextTestRunner 5 | 6 | from django.test import TestCase 7 | from django.test.runner import DiscoverRunner 8 | from test_query_counter.apps import RequestQueryCountConfig 9 | from test_query_counter.manager import RequestQueryCountManager 10 | from test_query_counter.query_count import (TestResultQueryContainer, 11 | exclude_query_count) 12 | 13 | 14 | class TestRunnerTest(TestCase): 15 | 16 | def setUp(self): 17 | # Simple class that doesn't output to the standard output 18 | class StringIOTextRunner(TextTestRunner): 19 | def __init__(self, *args, **kwargs): 20 | kwargs['stream'] = StringIO() 21 | super().__init__(*args, **kwargs) 22 | 23 | self.test_runner = DiscoverRunner() 24 | self.test_runner.test_runner = StringIOTextRunner 25 | 26 | def tearDown(self): 27 | try: 28 | os.remove(RequestQueryCountConfig.get_setting('DETAIL_PATH')) 29 | except FileNotFoundError: 30 | pass 31 | try: 32 | os.remove(RequestQueryCountConfig.get_setting('SUMMARY_PATH')) 33 | except FileNotFoundError: 34 | pass 35 | 36 | def test_empty_test(self): 37 | class Test(TestCase): 38 | def test_foo(self): 39 | pass 40 | 41 | def test_bar(self): 42 | pass 43 | 44 | self.test_runner.setup_test_environment() 45 | self.test_runner.run_suite(TestLoader().loadTestsFromTestCase( 46 | testCaseClass=Test) 47 | ) 48 | self.test_runner.teardown_test_environment() 49 | 50 | # check for empty tests 51 | self.assertIsNotNone(RequestQueryCountManager, 'queries') 52 | self.assertIsInstance(RequestQueryCountManager.queries, 53 | TestResultQueryContainer) 54 | self.assertEqual(RequestQueryCountManager.queries.total, 0) 55 | 56 | # check if files are generated 57 | self.assertTrue(path.exists( 58 | RequestQueryCountConfig.get_setting('SUMMARY_PATH')) 59 | ) 60 | self.assertTrue(path.isfile( 61 | RequestQueryCountConfig.get_setting('SUMMARY_PATH')) 62 | ) 63 | self.assertTrue(path.exists( 64 | RequestQueryCountConfig.get_setting('DETAIL_PATH')) 65 | ) 66 | self.assertTrue(path.isfile( 67 | RequestQueryCountConfig.get_setting('DETAIL_PATH')) 68 | ) 69 | 70 | @classmethod 71 | def get_id(cls, test_class, method_name): 72 | return "{}.{}.{}".format(test_class.__module__, 73 | test_class.__qualname__, 74 | method_name) 75 | 76 | def test_runner_include_queries(self): 77 | class Test(TestCase): 78 | def test_foo(self): 79 | self.client.get('/url-1') 80 | 81 | self.test_runner.run_tests( 82 | None, 83 | TestLoader().loadTestsFromTestCase(testCaseClass=Test) 84 | ) 85 | 86 | # Assert it ran one test 87 | self.assertEqual(len(RequestQueryCountManager.queries.queries_by_testcase), 1) 88 | 89 | test_foo_id = self.get_id(Test, 'test_foo') 90 | self.assertIn(test_foo_id, 91 | RequestQueryCountManager.queries.queries_by_testcase) 92 | 93 | self.assertEqual( 94 | RequestQueryCountManager.queries.queries_by_testcase[test_foo_id].total, 1 95 | ) 96 | 97 | def test_excluded_test(self): 98 | class Test(TestCase): 99 | @exclude_query_count() 100 | def test_foo(self): 101 | self.client.get('/url-1') 102 | 103 | def test_bar(self): 104 | self.client.get('/url-1') 105 | 106 | self.test_runner.run_suite( 107 | TestLoader().loadTestsFromTestCase(testCaseClass=Test) 108 | ) 109 | # Assert test_foo has excluded queries 110 | self.assertEqual( 111 | RequestQueryCountManager.queries.queries_by_testcase[ 112 | self.get_id(Test, 'test_foo')].total, 113 | 0 114 | ) 115 | # Assert test_bar has some queries 116 | self.assertEqual( 117 | RequestQueryCountManager.queries.queries_by_testcase[ 118 | self.get_id(Test, 'test_bar')].total, 119 | 1 120 | ) 121 | 122 | def test_excluded_class(self): 123 | @exclude_query_count() 124 | class Test(TestCase): 125 | def test_foo(self): 126 | self.client.get('path-1') 127 | 128 | def test_bar(self): 129 | self.client.get('path-1') 130 | 131 | self.test_runner.run_suite( 132 | TestLoader().loadTestsFromTestCase(testCaseClass=Test) 133 | ) 134 | # Assert test_foo has excluded queries 135 | self.assertEqual( 136 | RequestQueryCountManager.queries.queries_by_testcase[ 137 | self.get_id(Test, 'test_foo')].total, 138 | 0 139 | ) 140 | self.assertEqual( 141 | RequestQueryCountManager.queries.queries_by_testcase[ 142 | self.get_id(Test, 'test_bar')].total, 143 | 0 144 | ) 145 | 146 | def test_conditional_exclude(self): 147 | class Test(TestCase): 148 | @exclude_query_count(path='url-2') 149 | def test_exclude_path(self): 150 | self.client.get('/url-1') 151 | self.client.post('/url-2') 152 | 153 | @exclude_query_count(method='post') 154 | def test_exclude_method(self): 155 | self.client.get('/url-1') 156 | self.client.post('/url-2') 157 | 158 | @exclude_query_count(count=2) 159 | def test_exclude_count(self): 160 | self.client.get('/url-1') 161 | self.client.post('/url-2') 162 | # succesive url are additive 163 | self.client.put('/url-3') 164 | self.client.put('/url-3') 165 | self.client.put('/url-3') 166 | 167 | self.test_runner.run_suite( 168 | TestLoader().loadTestsFromTestCase(testCaseClass=Test) 169 | ) 170 | self.assertEqual( 171 | RequestQueryCountManager.queries.queries_by_testcase[ 172 | self.get_id(Test, 'test_exclude_path')].total, 173 | 1 174 | ) 175 | self.assertEqual( 176 | RequestQueryCountManager.queries.queries_by_testcase[ 177 | self.get_id(Test, 'test_exclude_method')].total, 178 | 1 179 | ) 180 | self.assertEqual( 181 | RequestQueryCountManager.queries.queries_by_testcase[ 182 | self.get_id(Test, 'test_exclude_count')].total, 183 | 3 184 | ) 185 | 186 | def test_nested_method_exclude(self): 187 | class Test(TestCase): 188 | @exclude_query_count(path='url-1') 189 | @exclude_query_count(method='post') 190 | @exclude_query_count(path='url-3') 191 | def test_foo(self): 192 | self.client.get('/url-1') 193 | self.client.post('/url-2') 194 | self.client.put('/url-3') 195 | 196 | self.test_runner.run_suite( 197 | TestLoader().loadTestsFromTestCase(testCaseClass=Test) 198 | ) 199 | self.assertEqual( 200 | RequestQueryCountManager.queries.queries_by_testcase[ 201 | self.get_id(Test, 'test_foo')].total, 202 | 0 203 | ) 204 | 205 | def test_nested_class_method_exclude(self): 206 | @exclude_query_count(path='url-1') 207 | class Test(TestCase): 208 | @exclude_query_count(method='post') 209 | def test_foo(self): 210 | self.client.get('/url-1') 211 | self.client.post('/url-2') 212 | self.client.put('/url-3') 213 | 214 | self.test_runner.run_suite( 215 | TestLoader().loadTestsFromTestCase(testCaseClass=Test) 216 | ) 217 | self.assertEqual( 218 | RequestQueryCountManager.queries.queries_by_testcase[ 219 | self.get_id(Test, 'test_foo')].total, 220 | 1 221 | ) 222 | 223 | def test_custom_setup_teardown(self): 224 | class Test(TestCase): 225 | def setUp(self): 226 | pass 227 | 228 | def tearDown(self): 229 | pass 230 | 231 | def test_foo(self): 232 | self.client.get('/url-1') 233 | 234 | self.test_runner.run_suite( 235 | TestLoader().loadTestsFromTestCase(testCaseClass=Test) 236 | ) 237 | self.assertIn( 238 | self.get_id(Test, 'test_foo'), 239 | RequestQueryCountManager.queries.queries_by_testcase 240 | ) 241 | self.assertEqual( 242 | RequestQueryCountManager.queries.queries_by_testcase[ 243 | self.get_id(Test, 'test_foo')].total, 244 | 1 245 | ) 246 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 2 | from __future__ import absolute_import, unicode_literals 3 | 4 | from django.conf.urls import url 5 | 6 | from tests.views import view1, view2 7 | 8 | urlpatterns = [ 9 | url(r'^url-1$', view1, name='view-1'), 10 | url(r'^url-2$', view2, name='view-2'), 11 | url(r'^url-3$', view2, name='view-3') 12 | ] 13 | -------------------------------------------------------------------------------- /tests/views.py: -------------------------------------------------------------------------------- 1 | from django.db import connection 2 | from django.http import HttpResponse 3 | 4 | 5 | def view1(request): 6 | with connection.cursor() as cursor: 7 | cursor.execute("SELECT 'foo'") 8 | cursor.fetchone() 9 | return HttpResponse('view1') 10 | 11 | 12 | def view2(request): 13 | with connection.cursor() as cursor: 14 | cursor.execute("SELECT 'bar'") 15 | cursor.fetchone() 16 | return HttpResponse('view2') 17 | 18 | 19 | def view3(request): 20 | with connection.cursor() as cursor: 21 | cursor.execute("SELECT 'baz'") 22 | cursor.fetchone() 23 | return HttpResponse('view2') 24 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | {py27,py33,py34,py35}-django-18 4 | {py27,py34,py35}-django-19 5 | {py27,py34,py35}-django-110 6 | 7 | [testenv] 8 | setenv = 9 | PYTHONPATH = {toxinidir}:{toxinidir}/test_query_counter 10 | commands = coverage run --source test_query_counter runtests.py 11 | deps = 12 | django-18: Django>=1.8,<1.9 13 | django-19: Django>=1.9,<1.10 14 | django-110: Django>=1.10 15 | -r{toxinidir}/requirements_test.txt 16 | basepython = 17 | py35: python3.5 18 | py34: python3.4 19 | py33: python3.3 20 | py27: python2.7 21 | --------------------------------------------------------------------------------