Commit d89eebc6 authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Add coverage contexts

parent 50903f2e
Loading
Loading
Loading
Loading
+12 −0
Original line number Diff line number Diff line
@@ -44,6 +44,15 @@ warn_unused_configs = true
warn_unreachable = true
mypy_path = ["stubs"]

[[tool.mypy.overrides]]
module = "coverage.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "tests.coverage"
disallow_subclassing_any = false


[tool.flakehell]
base = ".flakehell.toml"

@@ -54,6 +63,9 @@ branch = true
source = [
	"behave_utils",
]
plugins = [
	"tests.coverage",
]

[tool.coverage.report]
precision = 2

tests/coverage.py

0 → 100644
+47 −0
Original line number Diff line number Diff line
#  Copyright 2022  Dominik Sekotill <dom.sekotill@kodo.org.uk>
#
#  This Source Code Form is subject to the terms of the Mozilla Public
#  License, v. 2.0. If a copy of the MPL was not distributed with this
#  file, You can obtain one at http://mozilla.org/MPL/2.0/.

"""
Plugin module for test coverage
"""

from __future__ import annotations

from types import FrameType
from typing import Any
from unittest import TestCase

from coverage.plugin import CoveragePlugin
from coverage.plugin_support import Plugins


class DynamicContextPlugin(CoveragePlugin):
	"""
	A dynamic context plugin for coverage.py

	https://coverage.readthedocs.io/en/latest/contexts.html#dynamic-contexts

	This plugin annotates code lines with the names of tests under which the line was
	reached.
	"""

	def dynamic_context(self, frame: FrameType) -> str|None:  # noqa: D102
		if not frame.f_code.co_name.startswith("test"):
			return None
		try:
			inst = frame.f_locals["self"]
		except KeyError:
			return None
		if isinstance(inst, TestCase):
			return str(inst)
		return None


def coverage_init(reg: Plugins, options: dict[str, Any]) -> None:
	"""
	Initialise this plugin module
	"""
	reg.add_dynamic_context(DynamicContextPlugin())