[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci
This commit is contained in:
pre-commit-ci[bot] 2024-04-13 00:00:18 +00:00
parent 72ad6dc953
commit f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions

View file

@ -1,18 +1,20 @@
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Raw data collector for coverage.py."""
from __future__ import annotations
import functools
import os
import sys
from types import FrameType
from typing import (
cast, Any, Callable, Dict, List, Mapping, Set, TypeVar,
)
from typing import Any
from typing import Callable
from typing import cast
from typing import Dict
from typing import List
from typing import Mapping
from typing import Set
from typing import TypeVar
from coverage import env
from coverage.config import CoverageConfig
@ -20,13 +22,17 @@ from coverage.data import CoverageData
from coverage.debug import short_stack
from coverage.disposition import FileDisposition
from coverage.exceptions import ConfigError
from coverage.misc import human_sorted_items, isolate_module
from coverage.misc import human_sorted_items
from coverage.misc import isolate_module
from coverage.plugin import CoveragePlugin
from coverage.pytracer import PyTracer
from coverage.sysmon import SysMonitor
from coverage.types import (
TArc, TFileDisposition, TTraceData, TTraceFn, TracerCore, TWarnFn,
)
from coverage.types import TArc
from coverage.types import TFileDisposition
from coverage.types import TracerCore
from coverage.types import TTraceData
from coverage.types import TTraceFn
from coverage.types import TWarnFn
os = isolate_module(os)
@ -37,7 +43,7 @@ try:
HAS_CTRACER = True
except ImportError:
# Couldn't import the C extension, maybe it isn't built.
if os.getenv("COVERAGE_CORE") == "ctrace": # pragma: part covered
if os.getenv('COVERAGE_CORE') == 'ctrace': # pragma: part covered
# During testing, we use the COVERAGE_CORE environment variable
# to indicate that we've fiddled with the environment to test this
# fallback code. If we thought we had a C tracer, but couldn't import
@ -48,7 +54,7 @@ except ImportError:
sys.exit(1)
HAS_CTRACER = False
T = TypeVar("T")
T = TypeVar('T')
class Collector:
@ -73,7 +79,7 @@ class Collector:
_collectors: list[Collector] = []
# The concurrency settings we support here.
LIGHT_THREADS = {"greenlet", "eventlet", "gevent"}
LIGHT_THREADS = {'greenlet', 'eventlet', 'gevent'}
def __init__(
self,
@ -130,7 +136,7 @@ class Collector:
self.branch = branch
self.warn = warn
self.concurrency = concurrency
assert isinstance(self.concurrency, list), f"Expected a list: {self.concurrency!r}"
assert isinstance(self.concurrency, list), f'Expected a list: {self.concurrency!r}'
self.pid = os.getpid()
@ -147,12 +153,12 @@ class Collector:
core: str | None
if timid:
core = "pytrace"
core = 'pytrace'
else:
core = os.getenv("COVERAGE_CORE")
core = os.getenv('COVERAGE_CORE')
if core == "sysmon" and not env.PYBEHAVIOR.pep669:
self.warn("sys.monitoring isn't available, using default core", slug="no-sysmon")
if core == 'sysmon' and not env.PYBEHAVIOR.pep669:
self.warn("sys.monitoring isn't available, using default core", slug='no-sysmon')
core = None
if not core:
@ -160,25 +166,25 @@ class Collector:
# if env.PYBEHAVIOR.pep669 and self.should_start_context is None:
# core = "sysmon"
if HAS_CTRACER:
core = "ctrace"
core = 'ctrace'
else:
core = "pytrace"
core = 'pytrace'
if core == "sysmon":
if core == 'sysmon':
self._trace_class = SysMonitor
self._core_kwargs = {"tool_id": 3 if metacov else 1}
self._core_kwargs = {'tool_id': 3 if metacov else 1}
self.file_disposition_class = FileDisposition
self.supports_plugins = False
self.packed_arcs = False
self.systrace = False
elif core == "ctrace":
elif core == 'ctrace':
self._trace_class = CTracer
self._core_kwargs = {}
self.file_disposition_class = CFileDisposition
self.supports_plugins = True
self.packed_arcs = True
self.systrace = True
elif core == "pytrace":
elif core == 'pytrace':
self._trace_class = PyTracer
self._core_kwargs = {}
self.file_disposition_class = FileDisposition
@ -186,42 +192,42 @@ class Collector:
self.packed_arcs = False
self.systrace = True
else:
raise ConfigError(f"Unknown core value: {core!r}")
raise ConfigError(f'Unknown core value: {core!r}')
# We can handle a few concurrency options here, but only one at a time.
concurrencies = set(self.concurrency)
unknown = concurrencies - CoverageConfig.CONCURRENCY_CHOICES
if unknown:
show = ", ".join(sorted(unknown))
raise ConfigError(f"Unknown concurrency choices: {show}")
show = ', '.join(sorted(unknown))
raise ConfigError(f'Unknown concurrency choices: {show}')
light_threads = concurrencies & self.LIGHT_THREADS
if len(light_threads) > 1:
show = ", ".join(sorted(light_threads))
raise ConfigError(f"Conflicting concurrency settings: {show}")
show = ', '.join(sorted(light_threads))
raise ConfigError(f'Conflicting concurrency settings: {show}')
do_threading = False
tried = "nothing" # to satisfy pylint
tried = 'nothing' # to satisfy pylint
try:
if "greenlet" in concurrencies:
tried = "greenlet"
if 'greenlet' in concurrencies:
tried = 'greenlet'
import greenlet
self.concur_id_func = greenlet.getcurrent
elif "eventlet" in concurrencies:
tried = "eventlet"
elif 'eventlet' in concurrencies:
tried = 'eventlet'
import eventlet.greenthread # pylint: disable=import-error,useless-suppression
self.concur_id_func = eventlet.greenthread.getcurrent
elif "gevent" in concurrencies:
tried = "gevent"
elif 'gevent' in concurrencies:
tried = 'gevent'
import gevent # pylint: disable=import-error,useless-suppression
self.concur_id_func = gevent.getcurrent
if "thread" in concurrencies:
if 'thread' in concurrencies:
do_threading = True
except ImportError as ex:
msg = f"Couldn't trace with concurrency={tried}, the module isn't installed."
raise ConfigError(msg) from ex
if self.concur_id_func and not hasattr(self._trace_class, "concur_id_func"):
if self.concur_id_func and not hasattr(self._trace_class, 'concur_id_func'):
raise ConfigError(
"Can't support concurrency={} with {}, only threads are supported.".format(
tried, self.tracer_name(),
@ -238,7 +244,7 @@ class Collector:
self.reset()
def __repr__(self) -> str:
return f"<Collector at {id(self):#x}: {self.tracer_name()}>"
return f'<Collector at {id(self):#x}: {self.tracer_name()}>'
def use_data(self, covdata: CoverageData, context: str | None) -> None:
"""Use `covdata` for recording data."""
@ -296,7 +302,7 @@ class Collector:
#
# This gives a 20% benefit on the workload described at
# https://bitbucket.org/pypy/pypy/issue/1871/10x-slower-than-cpython-under-coverage
self.should_trace_cache = __pypy__.newdict("module")
self.should_trace_cache = __pypy__.newdict('module')
else:
self.should_trace_cache = {}
@ -394,9 +400,9 @@ class Collector:
"""Stop collecting trace information."""
assert self._collectors
if self._collectors[-1] is not self:
print("self._collectors:")
print('self._collectors:')
for c in self._collectors:
print(f" {c!r}\n{c.origin}")
print(f' {c!r}\n{c.origin}')
assert self._collectors[-1] is self, (
f"Expected current collector to be {self!r}, but it's {self._collectors[-1]!r}"
)
@ -414,9 +420,9 @@ class Collector:
tracer.stop()
stats = tracer.get_stats()
if stats:
print("\nCoverage.py tracer stats:")
print('\nCoverage.py tracer stats:')
for k, v in human_sorted_items(stats.items()):
print(f"{k:>20}: {v}")
print(f'{k:>20}: {v}')
if self.threading:
self.threading.settrace(None)
@ -433,7 +439,7 @@ class Collector:
def post_fork(self) -> None:
"""After a fork, tracers might need to adjust."""
for tracer in self.tracers:
if hasattr(tracer, "post_fork"):
if hasattr(tracer, 'post_fork'):
tracer.post_fork()
def _activity(self) -> bool:
@ -451,7 +457,7 @@ class Collector:
if self.static_context:
context = self.static_context
if new_context:
context += "|" + new_context
context += '|' + new_context
else:
context = new_context
self.covdata.set_context(context)
@ -462,7 +468,7 @@ class Collector:
assert file_tracer is not None
plugin = file_tracer._coverage_plugin
plugin_name = plugin._coverage_plugin_name
self.warn(f"Disabling plug-in {plugin_name!r} due to previous exception")
self.warn(f'Disabling plug-in {plugin_name!r} due to previous exception')
plugin._coverage_enabled = False
disposition.trace = False