diff --git a/.editorconfig b/.editorconfig index 88200b6..6e7851e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,5 +1,5 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt # This file is for unifying the coding style for different editors and IDEs. # More information at http://EditorConfig.org diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9e2cf1e..4deb5b5 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -12,45 +12,53 @@ on: # week, Sundays at 6:00 UTC. - cron: "0 6 * * 0" +permissions: + contents: read + +concurrency: + group: "${{ github.workflow }}-${{ github.ref }}" + cancel-in-progress: true defaults: run: shell: bash +env: + PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 # Get colored pytest output + jobs: tests: - name: "Python ${{ matrix.python-version }} on ${{ matrix.os }}" - runs-on: "${{ matrix.os }}" + name: "${{ matrix.python-version }} on ${{ matrix.os }}" + runs-on: "${{ matrix.os }}-latest" strategy: matrix: os: - - ubuntu-latest - - macos-latest - - windows-latest + - ubuntu + - macos + - windows python-version: # When changing this list, be sure to check the [gh-actions] list in # tox.ini so that tox will run properly. - - "2.7" - - "3.6" - - "3.7" - - "3.8" - - "3.9" - "3.10" - exclude: - # Windows 2.7 doesn't work because Microsoft removed stuff we needed. - - os: windows-latest - python-version: "2.7" + - "3.11" + - "3.12" + - "3.13" + - "3.14" fail-fast: false steps: - name: "Check out the repo" - uses: "actions/checkout@v2" + uses: "actions/checkout@v4" + with: + persist-credentials: false - name: "Set up Python" - uses: "actions/setup-python@v2" + uses: "actions/setup-python@v5" with: python-version: "${{ matrix.python-version }}" + allow-prereleases: true - name: "Install dependencies" run: | @@ -79,12 +87,14 @@ jobs: steps: - name: "Check out the repo" - uses: "actions/checkout@v2" + uses: "actions/checkout@v4" + with: + persist-credentials: false - name: "Set up Python" - uses: "actions/setup-python@v2" + uses: "actions/setup-python@v5" with: - python-version: "3.8" + python-version: "3.10" - name: "Install dependencies" run: | diff --git a/.isort.cfg b/.isort.cfg index ed14f2e..cd31999 100644 --- a/.isort.cfg +++ b/.isort.cfg @@ -4,4 +4,4 @@ force_grid_wrap=0 include_trailing_comma=True line_length=79 multi_line_output=3 -known_third_party = coverage,django,setuptools,six,unittest_mixins +known_third_party = coverage,django,setuptools,unittest_mixins diff --git a/MANIFEST.in b/MANIFEST.in index 74dd042..b220a56 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,15 +1,12 @@ # Licensed under the Apache 2.0 License # - http://www.apache.org/licenses/LICENSE-2.0 -# - https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# - https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt -exclude .isort.cfg -exclude howto.txt -exclude Makefile -exclude requirements.txt -exclude tox.ini -exclude .editorconfig -include AUTHORS.txt -include LICENSE.txt -include NOTICE.txt -include README.rst -prune tests +include *.txt +include .editorconfig +include .isort.cfg +include Makefile +include tox.ini + +recursive-include .github * +recursive-include tests *.py diff --git a/Makefile b/Makefile index 2113b40..8d302f0 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,10 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt # Makefile for django_coverage_plugin +.PHONY: help test clean sterile dist pypi test_pypi tag ghrelease + help: ## Show this help. @echo "Available targets:" @grep '^[a-zA-Z]' $(MAKEFILE_LIST) | sort | awk -F ':.*?## ' 'NF==2 {printf " %-26s%s\n", $$1, $$2}' @@ -24,14 +26,23 @@ clean: ## Remove non-source files. sterile: clean ## Remove all non-controlled content, even if expensive. -rm -rf .tox* - -kit: ## Make the source distribution. +dist: ## Make the source distribution. python -m build python -m twine check dist/* -kit_upload: ## Upload the built distributions to PyPI. +pypi: ## Upload the built distributions to PyPI. python -m twine upload --verbose dist/* -tag: ## Make a git tag with the version number - git tag -a -m "Version v$$(python setup.py --version)" v$$(python setup.py --version) +test_pypi: ## Upload the distributions to test PyPI. + python -m twine upload --verbose --repository testpypi --password $$TWINE_TEST_PASSWORD dist/* + +_install_e: + python -m pip install -q -e . + +tag: _install_e ## Make a git tag with the version number. + @export VER="$$(python -c "import django_coverage_plugin as me; print(me.__version__)")" && \ + git tag -s -m "Version v$$VER" v$$VER git push --all + +ghrelease: ## Make a GitHub release for the latest version. + python -m scriv github-release diff --git a/NOTICE.txt b/NOTICE.txt index 69e5a4f..7803be8 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -1,4 +1,4 @@ -Copyright 2015-2022 Ned Batchelder. All rights reserved. +Copyright 2015-2025 Ned Batchelder. All rights reserved. Except where noted otherwise, this software is licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in diff --git a/README.rst b/README.rst index caf761a..d6ef68f 100644 --- a/README.rst +++ b/README.rst @@ -1,6 +1,12 @@ -.. start-badges +================================== +Django Template Coverage.py Plugin +================================== + +A `coverage.py`_ plugin to measure test coverage of Django templates. -|status| |kit| |license| |versions| |djversions| +| |status| |kit| |license| +| |versions| |djversions| +| |sponsor| |bluesky-nedbat| |mastodon-nedbat| .. |status| image:: https://img.shields.io/pypi/status/django_coverage_plugin.svg :target: https://pypi.python.org/pypi/django_coverage_plugin @@ -14,27 +20,33 @@ .. |versions| image:: https://img.shields.io/pypi/pyversions/django_coverage_plugin.svg :target: https://pypi.python.org/pypi/django_coverage_plugin :alt: Supported Python Versions -.. |djversions| image:: https://img.shields.io/badge/Django-1.8%20%7C%201.11%20%7C%202.0%20%7C%202.1%20%7C%202.2%20%7C%203.0-44b78b.svg +.. the Django badge says: `3.2 | 4.2 | 5.2` +.. |djversions| image:: https://img.shields.io/badge/Django-3.2%20%7C%204.2%20%7C%205.2-44b78b.svg :target: https://pypi.python.org/pypi/django_coverage_plugin :alt: Supported Django Versions +.. |sponsor| image:: https://img.shields.io/badge/%E2%9D%A4-Sponsor%20me-brightgreen?style=flat&logo=GitHub + :target: https://github.com/sponsors/nedbat + :alt: Sponsor me on GitHub +.. |bluesky-nedbat| image:: https://img.shields.io/badge/dynamic/json?style=flat&color=96a3b0&labelColor=3686f7&logo=icloud&logoColor=white&label=@nedbat&url=https%3A%2F%2Fpublic.api.bsky.app%2Fxrpc%2Fapp.bsky.actor.getProfile%3Factor=nedbat.com&query=followersCount + :target: https://bsky.app/profile/nedbat.com + :alt: nedbat on Bluesky +.. |mastodon-nedbat| image:: https://img.shields.io/badge/dynamic/json?style=flat&labelColor=450657&logo=mastodon&logoColor=ffffff&label=@nedbat&query=followers_count&url=https%3A%2F%2Fhachyderm.io%2Fapi%2Fv1%2Faccounts%2Flookup%3Facct=nedbat + :target: https://hachyderm.io/@nedbat + :alt: nedbat on Mastodon -.. end-badges -================================== -Django Template Coverage.py Plugin -================================== -A `coverage.py`_ plugin to measure test coverage of Django templates. +Supported on: -Supported Python versions: 2.7, and 3.6 through 3.10. +- Python: 3.10 through 3.14. -Supported Django versions: 1.8, 1.11, 2.x, 3.x and 4.x. +- Django: 3.2 through 5.2. -Supported coverage.py versions: 4.x or higher. +- Coverage.py: 6.x or higher. -The plugin is pip installable:: +The plugin is pip-installable:: - $ pip install django_coverage_plugin + $ python3 -m pip install django_coverage_plugin To run it, add this setting to your ``.coveragerc`` file:: @@ -44,8 +56,7 @@ To run it, add this setting to your ``.coveragerc`` file:: Then run your tests under `coverage.py`_. You will see your templates listed in your coverage report along with -your Python modules. Please use `coverage.py`_ v4.4 or greater to allow -the plugin to identify untested templates. +your Python modules. If you get a :code:`django.core.exceptions.ImproperlyConfigured` error, you need to set the :code:`DJANGO_SETTINGS_MODULE` environment variable. @@ -123,17 +134,50 @@ Tests To run the tests:: - $ pip install -r requirements.txt + $ python3 -m pip install -r requirements.txt $ tox History ~~~~~~~ +.. scriv-insert-here + +v3.2.0 — 2025-10-05 +------------------- + +Drop Python 3.9 and Django 2.2. Add Python 3.14. + + +v3.1.1 — 2025-06-15 +------------------- + +Support changes: dropped Python 3.8, added Python 3.13. Added Django 5.2. + + +v3.1.0 — 2023-07-10 +------------------- + +Dropped support for Python 3.7 and Django 1.x. Declared support for Python +3.12. + + +v3.0.0 — 2022-12-06 +------------------- + +Dropped support for Python 2.7, Python 3.6, and Django 1.8. + + +v2.0.4 — 2022-10-31 +------------------- + +Declare our support for Python 3.11 and Django 4.1. + + v2.0.3 — 2022-05-04 ------------------- -Add support for Django 4.0 +Add support for Django 4.0. v2.0.2 — 2021-11-11 @@ -147,7 +191,7 @@ ignore_errors=True`` (`issue 78`_). When using ``source=.``, an existing coverage HTML report directory would be found and believed to be unmeasured HTML template files. This is now fixed. -.. _issue 78: https://github.com/nedbat/django_coverage_plugin/issues/78 +.. _issue 78: https://github.com/coveragepy/django_coverage_plugin/issues/78 v2.0.1 — 2021-10-06 @@ -170,9 +214,9 @@ case-sensitively, causing templates to be missed (`issue 46`_). Fix an issue (`issue 63`_) where tag libraries can't be found if imported during test collection. Thanks to Daniel Izquierdo for the fix. -.. _issue 46: https://github.com/nedbat/django_coverage_plugin/issues/46 -.. _issue 60: https://github.com/nedbat/django_coverage_plugin/issues/60 -.. _issue 63: https://github.com/nedbat/django_coverage_plugin/issues/63 +.. _issue 46: https://github.com/coveragepy/django_coverage_plugin/issues/46 +.. _issue 60: https://github.com/coveragepy/django_coverage_plugin/issues/60 +.. _issue 63: https://github.com/coveragepy/django_coverage_plugin/issues/63 v1.8.0 — 2020-01-23 ------------------- @@ -222,6 +266,7 @@ v1.4.2 — 2017-02-06 Fixes another instance of `issue 32`_, which was the result of an initialization order problem. +.. _issue 32: https://github.com/coveragepy/django_coverage_plugin/issues/32 v1.4.1 — 2017-01-25 @@ -230,9 +275,6 @@ v1.4.1 — 2017-01-25 Fixes `issue 32`_, which was the result of an initialization order problem. -.. _issue 32: https://github.com/nedbat/django_coverage_plugin/issues/32 - - v1.4 — 2017-01-16 ----------------- @@ -246,8 +288,8 @@ Only the ``django.template.backends.django.DjangoTemplates`` template engine is supported, and it must be configured with ``['OPTIONS']['debug'] = True``. Fixes `issue 27`_. -.. _issue 28: https://github.com/nedbat/django_coverage_plugin/issues/28 -.. _issue 27: https://github.com/nedbat/django_coverage_plugin/issues/27 +.. _issue 28: https://github.com/coveragepy/django_coverage_plugin/issues/28 +.. _issue 27: https://github.com/coveragepy/django_coverage_plugin/issues/27 @@ -257,7 +299,7 @@ v1.3.1 — 2016-06-02 Settings are read slightly differently, so as to not interfere with programs that don't need settings. Fixes `issue 18`_. -.. _issue 18: https://github.com/nedbat/django_coverage_plugin/issues/18 +.. _issue 18: https://github.com/coveragepy/django_coverage_plugin/issues/18 @@ -293,7 +335,7 @@ plugin, and fixes `issue 17`_. Potential Django 1.9 support is included, but the patch to Django hasn't been applied yet. -.. _issue 17: https://github.com/nedbat/django_coverage_plugin/issues/17 +.. _issue 17: https://github.com/coveragepy/django_coverage_plugin/issues/17 diff --git a/django_coverage_plugin/__init__.py b/django_coverage_plugin/__init__.py index bac9149..f346811 100644 --- a/django_coverage_plugin/__init__.py +++ b/django_coverage_plugin/__init__.py @@ -1,8 +1,10 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Django Template Coverage Plugin""" +__version__ = "3.2.0" + from .plugin import DjangoTemplatePluginException # noqa from .plugin import DjangoTemplatePlugin diff --git a/django_coverage_plugin/plugin.py b/django_coverage_plugin/plugin.py index 72b48e6..13e9c41 100644 --- a/django_coverage_plugin/plugin.py +++ b/django_coverage_plugin/plugin.py @@ -1,48 +1,18 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """The Django template coverage plugin.""" -from __future__ import print_function - import os.path import re -try: - from coverage.exceptions import NoSource -except ImportError: - # for coverage 5.x - from coverage.misc import NoSource import coverage.plugin import django import django.template -from django.template.base import Lexer, NodeList, Template, TextNode +from coverage.exceptions import NoSource +from django.template.base import Lexer, NodeList, Template, TextNode, TokenType from django.template.defaulttags import VerbatimNode from django.templatetags.i18n import BlockTranslateNode -from six.moves import range - -try: - from django.template.base import TokenType - - def _token_name(token_type): - token_type.name.capitalize() - -except ImportError: - # Django <2.1 uses separate constants for token types - from django.template.base import ( - TOKEN_BLOCK, - TOKEN_MAPPING, - TOKEN_TEXT, - TOKEN_VAR, - ) - - class TokenType: - TEXT = TOKEN_TEXT - VAR = TOKEN_VAR - BLOCK = TOKEN_BLOCK - - def _token_name(token_type): - return TOKEN_MAPPING[token_type] class DjangoTemplatePluginException(Exception): @@ -99,39 +69,28 @@ def check_debug(): return True -if django.VERSION < (1, 8): - raise RuntimeError("Django Coverage Plugin requires Django 1.8 or higher") +if django.VERSION < (3, 0): + raise RuntimeError("Django Coverage Plugin requires Django 3.x or higher") -if django.VERSION >= (1, 9): - # Since we are grabbing at internal details, we have to adapt as they - # change over versions. - def filename_for_frame(frame): - try: - return frame.f_locals["self"].origin.name - except (KeyError, AttributeError): - return None +# Since we are grabbing at internal details, we have to adapt as they +# change over versions. +def filename_for_frame(frame): + try: + return frame.f_locals["self"].origin.name + except (KeyError, AttributeError): + return None - def position_for_node(node): - try: - return node.token.position - except AttributeError: - return None - def position_for_token(token): - return token.position -else: - def filename_for_frame(frame): - try: - return frame.f_locals["self"].source[0].name - except (KeyError, AttributeError, IndexError): - return None +def position_for_node(node): + try: + return node.token.position + except AttributeError: + return None - def position_for_node(node): - return node.source[1] - def position_for_token(token): - return token.source[1] +def position_for_token(token): + return token.position def read_template_source(filename): @@ -143,14 +102,8 @@ def read_template_source(filename): if not settings.configured: settings.configure() - with open(filename, "rb") as f: - # The FILE_CHARSET setting will be removed in 3.1: - # https://docs.djangoproject.com/en/3.0/ref/settings/#file-charset - if django.VERSION >= (3, 1): - charset = 'utf-8' - else: - charset = settings.FILE_CHARSET - text = f.read().decode(charset) + with open(filename, "r", encoding="utf-8") as f: + text = f.read() return text @@ -178,7 +131,7 @@ def sys_info(self): return [ ("django_template_dir", self.django_template_dir), ("environment", sorted( - ("%s = %s" % (k, v)) + ("{} = {}".format(k, v)) for k, v in os.environ.items() if "DJANGO" in k )), @@ -252,7 +205,7 @@ def line_number_range(self, frame): return -1, -1 if SHOW_TRACING: - print("{!r}: {}".format(render_self, position)) + print(f"{render_self!r}: {position}") s_start, s_end = position if isinstance(render_self, TextNode): first_line = render_self.s.splitlines(True)[0] @@ -307,7 +260,7 @@ def get_line_map(self, filename): class FileReporter(coverage.plugin.FileReporter): def __init__(self, filename): - super(FileReporter, self).__init__(filename) + super().__init__(filename) # TODO: html filenames are absolute. self._source = None @@ -316,20 +269,17 @@ def source(self): if self._source is None: try: self._source = read_template_source(self.filename) - except (IOError, UnicodeError) as exc: - raise NoSource("Couldn't read {}: {}".format(self.filename, exc)) + except (OSError, UnicodeError) as exc: + raise NoSource(f"Couldn't read {self.filename}: {exc}") return self._source def lines(self): source_lines = set() if SHOW_PARSING: - print("-------------- {}".format(self.filename)) + print(f"-------------- {self.filename}") - if django.VERSION >= (1, 9): - lexer = Lexer(self.source()) - else: - lexer = Lexer(self.source(), self.filename) + lexer = Lexer(self.source()) tokens = lexer.tokenize() # Are we inside a comment? @@ -343,7 +293,7 @@ def lines(self): if SHOW_PARSING: print( "%10s %2d: %r" % ( - _token_name(token.token_type), + token.token_type.capitalize(), token.lineno, token.contents, ) @@ -402,7 +352,7 @@ def lines(self): source_lines.update(range(lineno, lineno+num_lines)) if SHOW_PARSING: - print("\t\t\tNow source_lines is: {!r}".format(source_lines)) + print(f"\t\t\tNow source_lines is: {source_lines!r}") return source_lines diff --git a/howto.txt b/howto.txt index 4481256..f0f4bd7 100644 --- a/howto.txt +++ b/howto.txt @@ -1,7 +1,7 @@ * Release checklist -- Version number in setup.py -- Classifiers in setup.py +- Version number in __init__.py +- Classifiers in pyproject.toml https://pypi.python.org/pypi?%3Aaction=list_classifiers eg: Development Status :: 3 - Alpha @@ -9,7 +9,8 @@ - Copyright date in NOTICE.txt - Update README.rst with latest changes - Kits: - $ make clean kit - $ make kit_upload + $ make clean dist + $ make test_pypi + $ make pypi $ make tag -- make a new gh release: https://github.com/nedbat/django_coverage_plugin/releases/new + $ make ghrelease diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..0c7292f --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,65 @@ +# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt + +[build-system] +requires = ["setuptools>=77.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "django_coverage_plugin" +description = "Django template coverage.py plugin" +readme = "README.rst" +authors = [ + {name = "Ned Batchelder", email = "ned@nedbatchelder.com"}, +] +license = "Apache-2.0" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "Framework :: Django", + "Framework :: Django :: 3.2", + "Framework :: Django :: 4.2", + "Framework :: Django :: 5.2", + "Intended Audience :: Developers", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Software Development :: Quality Assurance", + "Topic :: Software Development :: Testing", +] +requires-python = ">= 3.10" +dependencies = [ + "coverage", + "Django", +] +dynamic = ["version"] + +[project.urls] +"Homepage" = "https://github.com/coveragepy/django_coverage_plugin" +"Bug Tracker" = "https://github.com/coveragepy/django_coverage_plugin/issues" +"Source" = "https://github.com/coveragepy/django_coverage_plugin" + +[tool.setuptools.dynamic] +version = {attr = "django_coverage_plugin.__version__"} + +[tool.setuptools.packages.find] +include = ["django_coverage_plugin*"] + +[tool.pytest.ini_options] +# How come these warnings are suppressed successfully here, but not in conftest.py?? +filterwarnings = [ + # ignore all DeprecationWarnings... + "ignore::DeprecationWarning", + # ...but show them if they are from our code. + "default::DeprecationWarning:django_coverage_plugin", +] + +[tool.scriv] +fragment_directory = "scriv.d" +output_file = "README.rst" +rst_header_chars = "-." diff --git a/requirements.txt b/requirements.txt index 43e1737..fe664e8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,7 @@ -# To run tests, we just need tox. -tox >= 1.8 +# To run tests, we just need tox: +tox + +# For releases: build +scriv twine diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 679b318..0000000 --- a/setup.cfg +++ /dev/null @@ -1,10 +0,0 @@ -# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt - -[tool:pytest] -# How come these warnings are suppressed successfully here, but not in conftest.py?? -filterwarnings = - # ignore all DeprecationWarnings... - ignore::DeprecationWarning - # ...but show them if they are from our code. - default::DeprecationWarning:django_coverage_plugin diff --git a/setup.py b/setup.py deleted file mode 100644 index d5fb17b..0000000 --- a/setup.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- -"""Setup for Django Coverage Plugin - -Licensed under the Apache 2.0 License -- http://www.apache.org/licenses/LICENSE-2.0 -- https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt - -""" -from __future__ import absolute_import, print_function - -import io -import re -from os.path import dirname, join - -from setuptools import setup - - -def read(*names, **kwargs): - """Read and return contents of file - - Parameter: encoding kwarg may be set - """ - return io.open( - join(dirname(__file__), *names), - encoding=kwargs.get('encoding', 'utf8') - ).read() - - -classifiers = """\ -Environment :: Console -Intended Audience :: Developers -License :: OSI Approved :: Apache Software License -Operating System :: OS Independent -Programming Language :: Python :: 2.7 -Programming Language :: Python :: 3.6 -Programming Language :: Python :: 3.7 -Programming Language :: Python :: 3.8 -Programming Language :: Python :: 3.9 -Programming Language :: Python :: 3.10 -Programming Language :: Python :: Implementation :: CPython -Programming Language :: Python :: Implementation :: PyPy -Topic :: Software Development :: Quality Assurance -Topic :: Software Development :: Testing -Development Status :: 5 - Production/Stable -Framework :: Django -Framework :: Django :: 1.8 -Framework :: Django :: 1.11 -Framework :: Django :: 2.2 -Framework :: Django :: 3.2 -Framework :: Django :: 4.0 -""" - -setup( - name='django_coverage_plugin', - version='2.0.3', - description='Django template coverage.py plugin', - long_description=( - re.compile( - '^.. start-badges.*^.. end-badges', - re.M | re.S, - ).sub('', read('README.rst')) - ), - long_description_content_type='text/x-rst', - author='Ned Batchelder', - author_email='ned@nedbatchelder.com', - url='https://github.com/nedbat/django_coverage_plugin', - packages=['django_coverage_plugin'], - install_requires=[ - 'coverage', - 'six >= 1.4.0', - ], - license='Apache 2.0', - classifiers=classifiers.splitlines(), -) diff --git a/tests/__init__.py b/tests/__init__.py index 2d2b590..d4318d5 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,5 +1,5 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """The tests for the Django Coverage Plugin.""" diff --git a/tests/banner.py b/tests/banner.py index 2febc6e..8200b15 100644 --- a/tests/banner.py +++ b/tests/banner.py @@ -1,18 +1,18 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """For printing the versions from tox.ini.""" -from __future__ import print_function - import platform +import coverage import django print( - "{} {}; Django {}".format( + "{} {}; Django {}; Coverage {}".format( platform.python_implementation(), platform.python_version(), - django.get_version() + django.get_version(), + coverage.__version__, ) ) diff --git a/tests/conftest.py b/tests/conftest.py index 0852e87..5c8f6d7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,5 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """ Pytest auto configuration. diff --git a/tests/plugin_test.py b/tests/plugin_test.py index 1798971..f103454 100644 --- a/tests/plugin_test.py +++ b/tests/plugin_test.py @@ -1,5 +1,5 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Base classes and helpers for testing the plugin.""" @@ -21,7 +21,7 @@ from django_coverage_plugin.plugin import DjangoTemplatePlugin -def test_settings(): +def get_test_settings(): """Create a dict full of default Django settings for the tests.""" the_settings = { 'CACHES': { @@ -53,14 +53,10 @@ def test_settings(): ], }) - if django.VERSION < (1, 10): - # for {% ssi %} - the_settings['TEMPLATES'][0]['OPTIONS']['allowed_include_roots'] = [""] - return the_settings -settings.configure(**test_settings()) +settings.configure(**get_test_settings()) if hasattr(django, "setup"): django.setup() @@ -70,11 +66,11 @@ class DjangoPluginTestCase(StdStreamCapturingMixin, TempDirMixin, TestCase): """A base class for all our tests.""" def setUp(self): - super(DjangoPluginTestCase, self).setUp() + super().setUp() self.template_directory = "templates" def _path(self, name=None): - return "{}/{}".format(self.template_directory, name or self.template_file) + return f"{self.template_directory}/{name or self.template_file}" def make_template(self, text, name=None): """Make a template with `text`. @@ -195,14 +191,14 @@ def assert_analysis(self, executable, missing=None, name=None): self.assertEqual( executable, actual_executable, - "Executable lines aren't as expected: %r != %r" % ( + "Executable lines aren't as expected: {!r} != {!r}".format( executable, actual_executable, ), ) self.assertEqual( missing or [], actual_missing, - "Missing lines aren't as expected: %r != %r" % ( + "Missing lines aren't as expected: {!r} != {!r}".format( missing, actual_missing, ), ) @@ -230,31 +226,52 @@ def get_xml_report(self, name=None): return xml_coverage @contextlib.contextmanager - def assert_plugin_disabled(self, msg): - """Assert that our plugin was disabled during an operation.""" - # self.run_django_coverage will raise PluginDisabled if the plugin - # was disabled. + def assert_coverage_warnings(self, *msgs, min_cov=None): + """Assert that coverage.py warnings are raised that contain all msgs. + + If coverage version isn't at least min_cov, then no warnings are expected. + + """ # Coverage.py 6.0 made the warnings real warnings, so we have to adapt # how we test the warnings based on the version. - if coverage.version.version_info >= (6, 0): + if min_cov is not None and coverage.version_info < min_cov: + # Don't check for warnings on lower versions of coverage + yield + return + elif coverage.version_info >= (6, 0): import coverage.exceptions as cov_exc ctxmgr = self.assertWarns(cov_exc.CoverageWarning) else: - ctxmgr = nullcontext() + ctxmgr = contextlib.nullcontext() with ctxmgr as cw: - with self.assertRaises(PluginDisabled): - yield + yield if cw is not None: warn_text = "\n".join(str(w.message) for w in cw.warnings) else: warn_text = self.stderr() - self.assertIn( - "Disabling plug-in 'django_coverage_plugin.DjangoTemplatePlugin' " - "due to an exception:", - warn_text - ) - self.assertIn("DjangoTemplatePluginException: " + msg, warn_text) + for msg in msgs: + self.assertIn(msg, warn_text) + + @contextlib.contextmanager + def assert_plugin_disabled(self, msg): + """Assert that our plugin was disabled during an operation.""" + # self.run_django_coverage will raise PluginDisabled if the plugin + # was disabled. + msgs = [ + "Disabling plug-in 'django_coverage_plugin.DjangoTemplatePlugin' due to an exception:", + "DjangoTemplatePluginException: " + msg, + ] + with self.assert_coverage_warnings(*msgs): + with self.assertRaises(PluginDisabled): + yield + + @contextlib.contextmanager + def assert_no_data(self, min_cov=None): + """Assert that coverage warns no data was collected.""" + warn_msg = "No data was collected. (no-data-collected)" + with self.assert_coverage_warnings(warn_msg, min_cov=min_cov): + yield def squashed(s): @@ -293,9 +310,3 @@ def test_thing(self): class PluginDisabled(Exception): """Raised if we find that our plugin has been disabled.""" pass - - -@contextlib.contextmanager -def nullcontext(): - """For when we need a context manager to do nothing.""" - yield None diff --git a/tests/test_engines.py b/tests/test_engines.py index 76c713f..3bdbe32 100644 --- a/tests/test_engines.py +++ b/tests/test_engines.py @@ -1,5 +1,5 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Tests of multiple engines for django_coverage_plugin.""" @@ -10,7 +10,7 @@ class MultipleEngineTests(DjangoPluginTestCase): def setUp(self): - super(MultipleEngineTests, self).setUp() + super().setUp() engine = { 'NAME': 'other', @@ -33,7 +33,8 @@ def test_file_template(self): self.assert_analysis([1]) def test_string_template(self): - text = self.run_django_coverage(text='Hello', using='other') + with self.assert_no_data(): + text = self.run_django_coverage(text='Hello', using='other') self.assertEqual(text, 'Hello') def test_third_engine_not_debug(self): diff --git a/tests/test_extends.py b/tests/test_extends.py index a4922db..3f7a987 100644 --- a/tests/test_extends.py +++ b/tests/test_extends.py @@ -1,9 +1,9 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Tests of template inheritance for django_coverage_plugin.""" -from .plugin_test import DjangoPluginTestCase, django_stop_before +from .plugin_test import DjangoPluginTestCase class BlockTest(DjangoPluginTestCase): @@ -146,43 +146,3 @@ def test_include(self): self.assertEqual(text, "First\nInside\nJob\n\nLast\n") self.assert_analysis([1, 2, 3], name="outer.html") self.assert_analysis([1, 2], name="nested.html") - - -# {% ssi %} is in earlier Djangos than 1.9, but doesn't trace properly. -@django_stop_before(1, 10) -class SsiTest(DjangoPluginTestCase): - """Test {% ssi %}, which does not trace the included file.""" - - def test_ssi_unparsed(self): - nested = self.make_template(name="nested.html", text="""\ - Inside {{ a }} - Job - """) - - self.make_template(name="outer.html", text="""\ - First - {% ssi "NESTED" %} - Last - """.replace("NESTED", nested)) - - text = self.run_django_coverage(name="outer.html", context={'a': 17}) - self.assertEqual(text, "First\nInside {{ a }}\nJob\n\nLast\n") - self.assert_analysis([1, 2, 3], name="outer.html") - self.assert_measured_files("outer.html", "nested.html") - - def test_ssi_parsed(self): - nested = self.make_template(name="nested.html", text="""\ - Inside {{ a }} - Job - """) - - self.make_template(name="outer.html", text="""\ - First - {% ssi "NESTED" parsed %} - Last - """.replace("NESTED", nested)) - - text = self.run_django_coverage(name="outer.html", context={'a': 17}) - self.assertEqual(text, "First\nInside 17\nJob\n\nLast\n") - self.assert_analysis([1, 2, 3], name="outer.html") - self.assert_measured_files("outer.html", "nested.html") diff --git a/tests/test_flow.py b/tests/test_flow.py index 2a00709..db83fa8 100644 --- a/tests/test_flow.py +++ b/tests/test_flow.py @@ -1,5 +1,5 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Tests of control-flow structures for django_coverage_plugin.""" diff --git a/tests/test_helpers.py b/tests/test_helpers.py index d0e919c..467d879 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -1,5 +1,5 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Test helpers for the django coverage plugin.""" diff --git a/tests/test_html.py b/tests/test_html.py index c22ac00..b71537b 100644 --- a/tests/test_html.py +++ b/tests/test_html.py @@ -1,6 +1,5 @@ -# coding: utf8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Tests of HTML reporting for django_coverage_plugin.""" diff --git a/tests/test_i18n.py b/tests/test_i18n.py index e68b920..40affec 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -1,5 +1,5 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Tests of i18n tags for django_coverage_plugin.""" diff --git a/tests/test_settings.py b/tests/test_settings.py index c3ef4d5..5314051 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -1,22 +1,22 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Settings tests for django_coverage_plugin.""" from django.test.utils import override_settings -from .plugin_test import DjangoPluginTestCase, test_settings +from .plugin_test import DjangoPluginTestCase, get_test_settings # Make settings overrides for tests below. NON_DJANGO_BACKEND = 'django.template.backends.dummy.TemplateStrings' -DEBUG_FALSE_OVERRIDES = test_settings() +DEBUG_FALSE_OVERRIDES = get_test_settings() DEBUG_FALSE_OVERRIDES['TEMPLATES'][0]['OPTIONS']['debug'] = False -NO_OPTIONS_OVERRIDES = test_settings() +NO_OPTIONS_OVERRIDES = get_test_settings() del NO_OPTIONS_OVERRIDES['TEMPLATES'][0]['OPTIONS'] -OTHER_ENGINE_OVERRIDES = test_settings() +OTHER_ENGINE_OVERRIDES = get_test_settings() OTHER_ENGINE_OVERRIDES['TEMPLATES'][0]['BACKEND'] = NON_DJANGO_BACKEND OTHER_ENGINE_OVERRIDES['TEMPLATES'][0]['OPTIONS'] = {} diff --git a/tests/test_simple.py b/tests/test_simple.py index 7ca9188..c4e326d 100644 --- a/tests/test_simple.py +++ b/tests/test_simple.py @@ -1,13 +1,12 @@ -# coding: utf8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Simple tests for django_coverage_plugin.""" from .plugin_test import DjangoPluginTestCase # 200 Unicode chars: snowman + poo. -UNIUNI = u"\u26C4\U0001F4A9"*100 +UNIUNI = "\u26C4\U0001F4A9"*100 if isinstance(UNIUNI, str): UNISTR = UNIUNI else: @@ -64,8 +63,8 @@ def test_non_ascii(self): υηιcσɗє ιѕ тяιcку {{more}}! """) - text = self.run_django_coverage(context={'more': u'ɘboɔinU'}) - self.assertEqual(text, u'υηιcσɗє ιѕ тяιcку\nɘboɔinU!\n') + text = self.run_django_coverage(context={'more': 'ɘboɔinU'}) + self.assertEqual(text, 'υηιcσɗє ιѕ тяιcку\nɘboɔinU!\n') self.assert_analysis([1, 2]) self.assertEqual(self.get_html_report(), 100) self.assertEqual(self.get_xml_report(), 100) @@ -215,8 +214,8 @@ def test_verbatim(self): text = self.run_django_coverage() self.assertEqual( text, - u"1\n\n{{if dying}}Alive.{{/if}}\nsecond.\n" - u"{%third%}.UNIUNI\n\n7\n".replace(u"UNIUNI", UNIUNI) + "1\n\n{{if dying}}Alive.{{/if}}\nsecond.\n" + "{%third%}.UNIUNI\n\n7\n".replace("UNIUNI", UNIUNI) ) self.assert_analysis([1, 2, 3, 4, 5, 7]) @@ -245,11 +244,14 @@ class StringTemplateTest(DjangoPluginTestCase): run_in_temp_dir = False def test_string_template(self): - text = self.run_django_coverage( - text="Hello, {{name}}!", - context={'name': 'World'}, - options={}, - ) + # I don't understand why coverage 6 warns about no data, + # but coverage 5 does not. + with self.assert_no_data(min_cov=(6, 0)): + text = self.run_django_coverage( + text="Hello, {{name}}!", + context={'name': 'World'}, + options={}, + ) self.assertEqual(text, "Hello, World!") diff --git a/tests/test_source.py b/tests/test_source.py index 80b53d4..e44c7ea 100644 --- a/tests/test_source.py +++ b/tests/test_source.py @@ -1,5 +1,5 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt """Tests of template inheritance for django_coverage_plugin.""" @@ -88,9 +88,9 @@ def test_non_utf8_error(self): text = self.run_django_coverage(name="main.html") self.assertEqual(text, "Hello") - self.assert_measured_files("main.html", "static{}changelog.txt".format(os.sep)) + self.assert_measured_files("main.html", f"static{os.sep}changelog.txt") self.assert_analysis([1], name="main.html") - with self.assertRaisesRegexp(NoSource, r"changelog.txt.*invalid start byte"): + with self.assertRaisesRegex(NoSource, r"changelog.txt.*invalid start byte"): self.cov.html_report() def test_non_utf8_omitted(self): @@ -110,7 +110,7 @@ def test_non_utf8_omitted(self): text = self.run_django_coverage(name="main.html") self.assertEqual(text, "Hello") - self.assert_measured_files("main.html", "static{}changelog.txt".format(os.sep)) + self.assert_measured_files("main.html", f"static{os.sep}changelog.txt") self.assert_analysis([1], name="main.html") self.cov.html_report() @@ -131,9 +131,14 @@ def test_non_utf8_ignored(self): text = self.run_django_coverage(name="main.html") self.assertEqual(text, "Hello") - self.assert_measured_files("main.html", "static{}changelog.txt".format(os.sep)) + self.assert_measured_files("main.html", f"static{os.sep}changelog.txt") self.assert_analysis([1], name="main.html") - self.cov.html_report() + warn_msg = ( + "'utf-8' codec can't decode byte 0xf6 in position 2: " + + "invalid start byte (couldnt-parse)" + ) + with self.assert_coverage_warnings(warn_msg, min_cov=(6, 0)): + self.cov.html_report() def test_htmlcov_isnt_measured(self): # We used to find the HTML report and think it was template files. diff --git a/tox.ini b/tox.ini index 50f9df3..1aae1d5 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 -# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt +# For details: https://github.com/coveragepy/django_coverage_plugin/blob/main/NOTICE.txt # tox configuration for django_coverage_plugin. # @@ -13,25 +13,26 @@ # [tox] +# When changing this, also update the classifiers in setup.py: envlist = - py27-django{18,111}, - py36-django{18,111,22,32}, - py37-django{22,32}, - py38-django{22,32,40,tip}, - py39-django{22,32,40,tip}, - py310-django{32,40,tip}, + py310-django{32,42,52}-cov{6,7,tip}, + py311-django{42,52}-cov{6,7,tip}, + py312-django{52,tip}-cov{7,tip}, + py313-django{52,tip}-cov{7,tip}, + py314-django{52,tip}-cov{7,tip}, check,pkgcheck,doc [testenv] deps = + cov6: coverage>=6.0,<7.0 + cov7: coverage>=7.0,<8.0 + covtip: git+https://github.com/nedbat/coveragepy.git + django32: Django>=3.2,<4.0 + django42: Django>=4.2,<5.0 + django52: Django>=5.2,<6.0 + djangotip: git+https://github.com/django/django.git pytest unittest-mixins==1.6 - django18: Django>=1.8,<1.9 - django111: Django>=1.11,<2.0 - django22: Django>=2.2,<3.0 - django32: Django>=3.2,<4.0 - django40: Django>=4.0,<4.1 - djangotip: https://github.com/django/django/archive/main.tar.gz commands = python -c "import tests.banner" @@ -41,14 +42,19 @@ usedevelop = True passenv = * +setenv = + # In later versions of Python, the default coverage.py core is sysmon, + # which doesn't support plugins like us. Force ctrace instead. + py3{12,13,14}: COVERAGE_CORE=ctrace + [testenv:check] deps = flake8 isort commands = - flake8 --max-line-length=100 setup.py django_coverage_plugin tests setup.py - isort --check-only --diff django_coverage_plugin tests setup.py + flake8 --max-line-length=100 django_coverage_plugin tests + isort --check-only --diff django_coverage_plugin tests [testenv:pkgcheck] skip_install = true @@ -69,13 +75,12 @@ deps = sphinx commands = - rst2html.py --strict README.rst /tmp/django_coverage_plugin_README.html + rst2html --strict README.rst /tmp/django_coverage_plugin_README.html [gh-actions] python = - 2.7: py27 - 3.6: py36 - 3.7: py37 - 3.8: py38 - 3.9: py39 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + 3.14: py314