Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 2 additions & 26 deletions tests/const/test_const_enum_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@
from tests._support import (ISOLATED_PREFIXES, purge_modules, reimport_once_per_class,
restore_modules, snapshot_modules)
from tests.const import census
# NOTE: test_const_enum_builtin_parity and the #923 provenance test import it from here.
from tests.vendor._crawler import normalize as _normalize

#: Test tier (#1958): exercises metaclass, ABC or enum machinery, which differs by
#: interpreter.
Expand Down Expand Up @@ -107,32 +109,6 @@
)


def _normalize(context: 'str') -> 'str':
"""Whitespace-normalise a rendered template the way the writer does.

:meth:`pcapkit.vendor.default.Vendor.__init__` rstrips every non-blank line,
drops whitespace-only lines, joins with ``\\n`` and writes the result with
:func:`print`, which restores the single trailing newline. Reproducing it
here is what lets a rendered template be compared against a committed module
character for character.

Args:
context: Rendered template text.

Returns:
The text as it would be written to ``pcapkit/const/``.

"""
lines = [] # type: list[str]
for line in context.splitlines():
if line:
if line.strip():
lines.append(line.rstrip())
else:
lines.append(line)
return '\n'.join(lines) + '\n'


def _iter_const_int_enums() -> 'list[type]':
"""Discover every :class:`~aenum.IntEnum` defined under :mod:`pcapkit.const`.

Expand Down
154 changes: 154 additions & 0 deletions tests/vendor/_crawler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# -*- coding: utf-8 -*-
"""Shared scaffolding for the crawler tests. C.f. #3148.

The modules under :file:`tests/vendor/`, and :mod:`tests.const.test_const_enum_lookup`,
render constant modules from recorded data and compare them with the committed files,
which takes the same few steps in each:

* :func:`import_from_checkout` -- import the crawler and constant modules, and skip
unless they come from this checkout. Compared against this repository's files, a
module imported from an installed copy elsewhere would be comparing two trees,
which is an environment mismatch rather than a defect.
* :func:`make_crawler` -- a crawler with the attributes
:meth:`Vendor.__init__ <pcapkit.vendor.default.Vendor.__init__>` sets, without its
fetch and the constant file it writes.
* :func:`normalize` -- the whitespace normalisation that write goes through.
* :func:`defined_crawlers` -- every crawler defined under :file:`pcapkit/vendor/`.

It is deliberately not named ``test_*``, and it imports :mod:`pcapkit` only when a
test calls it, after :func:`tests._support.reimport_once_per_class`.

"""
from __future__ import annotations

import importlib
import pathlib
import pkgutil
from typing import TYPE_CHECKING

if TYPE_CHECKING:
import unittest
from types import ModuleType
from typing import Any

__all__ = ['ROOT', 'import_from_checkout', 'make_crawler', 'normalize', 'is_crawler', 'defined_crawlers']

#: Repository root, i.e. the grandparent of the directory holding this file.
ROOT = pathlib.Path(__file__).resolve().parents[2]


def import_from_checkout(test: 'unittest.TestCase', *names: 'str') -> 'tuple[ModuleType, ...]':
"""Import ``names``, skipping ``test`` unless each comes from this checkout.

Args:
test: The test case to skip.
*names: Dotted names of the modules to import.

Returns:
The modules, in the order named.

"""
modules = tuple(importlib.import_module(name) for name in names)
for module in modules:
resolved = pathlib.Path(module.__file__).resolve() # type: ignore[arg-type]
if ROOT not in resolved.parents:
test.skipTest(f'{module.__name__} was imported from {resolved}, which is outside '
f'{ROOT}; install this checkout with `pip install -e .`, or set '
f'PYTHONPATH to it, to run this suite against it')
return modules


def make_crawler(klass: 'type[Any]', *args: 'Any') -> 'tuple[Any, Any]':
"""A ``klass`` crawler as :meth:`Vendor.__init__` would set it up.

``Vendor.__init__`` fetches over the network and *writes* the constant file
as a side effect of construction, neither of which a test has any business
doing, so the attributes it sets -- ``NAME``, ``DOCS`` and ``record`` -- are
set here instead.

Args:
klass: The crawler class.
*args: What to hand :meth:`~pcapkit.vendor.default.Vendor.request` in
place of a fetched page; nothing for a crawler with no ``LINK``.

Returns:
The crawler, and the data its ``request`` returned.

"""
vendor = klass.__new__(klass)
vendor.NAME = klass.__name__
vendor.DOCS = klass.__doc__
data = vendor.request(*args)
vendor.record = vendor.count(data)
return vendor, data


def normalize(context: 'str') -> 'str':
"""Apply the whitespace normalisation the generator writes files through.

:meth:`pcapkit.vendor.default.Vendor.__init__` does not write what
:meth:`~pcapkit.vendor.default.Vendor.context` returns verbatim: it strips
trailing whitespace from every non-blank line, drops whitespace-only lines
outright, and ends the file with a newline courtesy of :func:`print`. Byte
comparison against the committed file has to do the same, or it reports a
difference that regeneration would not produce.

Args:
context: Return value of :meth:`~pcapkit.vendor.default.Vendor.context`,
or any template rendered for a constant module.

Returns:
The text as the generator would have written it to disk.

"""
lines = [] # type: list[str]
for line in context.splitlines():
if line:
if line.strip():
lines.append(line.rstrip())
else:
lines.append(line)
return '\n'.join(lines) + '\n'


def is_crawler(obj: 'Any', base: 'type[Any]') -> 'bool':
"""Whether ``obj`` is a concrete crawler class.

:class:`~pcapkit.vendor.default.Vendor` itself is excluded: it is the
abstract base, it is exported from :mod:`pcapkit.vendor` for subclassing
rather than for running, and it is not in :attr:`__all__`.

Args:
obj: Anything a module exports.
base: :class:`~pcapkit.vendor.default.Vendor`, from the current import.

"""
return isinstance(obj, type) and issubclass(obj, base) and obj is not base


def defined_crawlers(vendor: 'ModuleType', base: 'type[Any]') -> 'dict[str, Any]':
"""Every crawler defined under :file:`pcapkit/vendor/`, by qualified name.

Discovered from the filesystem with :func:`pkgutil.walk_packages`, which
is the half of a comparison :attr:`__all__` cannot influence -- so a
crawler that exists and is not listed is still found.

A class is attributed to the module that *defines* it, i.e. where
``__module__`` points, so the re-exports every subpackage performs do not
each count as another crawler.

Args:
vendor: The :mod:`pcapkit.vendor` package, from the current import.
base: :class:`~pcapkit.vendor.default.Vendor`, from the current import.

"""
found = {} # type: dict[str, Any]
for info in pkgutil.walk_packages(vendor.__path__, prefix='pcapkit.vendor.'):
if any(part.startswith('_') for part in info.name.split('.')):
continue
module = importlib.import_module(info.name)
for name in getattr(module, '__all__', ()):
obj = getattr(module, name, None)
if is_crawler(obj, base) and obj.__module__ == info.name:
found[f'{info.name}.{name}'] = obj
return found
68 changes: 9 additions & 59 deletions tests/vendor/test_crawler_reachability_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@

import importlib
import importlib.util
import pathlib
import pkgutil
import unittest
from collections import Counter
from typing import TYPE_CHECKING

from tests._support import reimport_once_per_class
from tests.vendor._crawler import defined_crawlers, import_from_checkout, is_crawler

if TYPE_CHECKING:
from typing import Any
Expand All @@ -66,9 +66,6 @@
#: tree.
__tier__ = 'LATEST'

#: Repository root, i.e. the grandparent of the directory holding this file.
ROOT = pathlib.Path(__file__).resolve().parents[2]

#: Whether the crawler machinery is importable at all. Importing
#: :mod:`pcapkit.vendor` pulls in every subpackage only when :mod:`requests` and
#: :mod:`bs4` are installed: :mod:`pcapkit.vendor.default` imports
Expand Down Expand Up @@ -106,64 +103,17 @@ class CrawlerReachabilityTests(unittest.TestCase):

def setUp(self) -> None:
reimport_once_per_class(self)

import pcapkit
import pcapkit.vendor as vendor
from pcapkit.vendor.default import Vendor

# The whole assertion is "what is on disk in *this* checkout is reachable
# from this checkout's __all__". An installed copy imported from
# somewhere else would be comparing two trees, which is an environment
# mismatch rather than a defect -- hence a skip rather than a failure.
resolved = pathlib.Path(pcapkit.__file__).resolve()
if ROOT not in resolved.parents:
self.skipTest(f'pcapkit was imported from {resolved}, which is outside {ROOT}; '
f'install this checkout with `pip install -e .`, or set PYTHONPATH to '
f'it, to run this suite against it')

self.vendor = vendor
self.Vendor = Vendor

def _is_crawler(self, obj: 'Any') -> 'bool':
"""Whether ``obj`` is a concrete crawler class.

:class:`~pcapkit.vendor.default.Vendor` itself is excluded: it is the
abstract base, it is exported from :mod:`pcapkit.vendor` for subclassing
rather than for running, and it is not in :attr:`__all__`.

"""
return isinstance(obj, type) and issubclass(obj, self.Vendor) and obj is not self.Vendor

def _defined_crawlers(self) -> 'dict[str, Any]':
"""Every crawler defined under :file:`pcapkit/vendor/`, by qualified name.

Discovered from the filesystem with :func:`pkgutil.walk_packages`, which
is the half of the comparison :attr:`__all__` cannot influence -- the
point being to find a crawler that exists and is not listed.

A class is attributed to the module that *defines* it, i.e. where
``__module__`` points, so the re-exports every subpackage performs do not
each count as another crawler.

"""
found = {} # type: dict[str, Any]
for info in pkgutil.walk_packages(self.vendor.__path__, prefix='pcapkit.vendor.'):
if any(part.startswith('_') for part in info.name.split('.')):
continue
module = importlib.import_module(info.name)
for name in getattr(module, '__all__', ()):
obj = getattr(module, name, None)
if self._is_crawler(obj) and obj.__module__ == info.name:
found[f'{info.name}.{name}'] = obj
return found
self.vendor, default = import_from_checkout(self, 'pcapkit.vendor', 'pcapkit.vendor.default')
self.Vendor = default.Vendor

def _reachable_from(self, module: 'Any') -> 'dict[str, Any]':
"""The crawlers ``pcapkit-vendor`` would collect from ``module``.

The expression :func:`pcapkit.vendor.__main__.main` uses on both paths,
reproduced -- ``getattr(module, name) for name in module.__all__`` --
keyed by defining module and class name so the result is comparable with
:meth:`_defined_crawlers` regardless of the alias each is exported under.
:func:`~tests.vendor._crawler.defined_crawlers` regardless of the alias
each is exported under.

``main()`` itself is deliberately not called: it does not merely build the
list, it runs every crawler in it, which fetches from IANA and rewrites
Expand All @@ -173,7 +123,7 @@ def _reachable_from(self, module: 'Any') -> 'dict[str, Any]':
reachable = {} # type: dict[str, Any]
for name in module.__all__:
obj = getattr(module, name, None)
if self._is_crawler(obj):
if is_crawler(obj, self.Vendor):
reachable[f'{obj.__module__}.{obj.__name__}'] = obj
return reachable

Expand All @@ -188,7 +138,7 @@ def test_every_crawler_is_reachable_from_the_default_target_list(self) -> None:
# The bare `pcapkit-vendor` path, which is what cron-vendor.yml runs:
# every crawler on disk has to be in the list that run() is handed, or it
# silently never executes and its constant file goes stale.
defined = self._defined_crawlers()
defined = defined_crawlers(self.vendor, self.Vendor)
reachable = self._reachable_from(self.vendor)

unreachable = sorted(set(defined) - set(reachable))
Expand All @@ -205,7 +155,7 @@ def test_every_crawler_is_reachable_from_its_own_protocol_target(self) -> None:
# The `--target <name>` path, which reads the subpackage's __all__ rather
# than the root's. It is a separate list and can be separately wrong, so a
# crawler can be reachable one way and not the other.
defined = self._defined_crawlers()
defined = defined_crawlers(self.vendor, self.Vendor)

reachable = {} # type: dict[str, Any]
for target in self._subpackages():
Expand Down Expand Up @@ -261,7 +211,7 @@ def test_handover_initiate_status_is_reachable(self) -> None:

module = importlib.import_module(module_name)
crawler = getattr(module, class_name)
self.assertTrue(self._is_crawler(crawler))
self.assertTrue(is_crawler(crawler, self.Vendor))

import pcapkit.vendor.mh as mh
self.assertIn(exported, mh.__all__)
Expand Down
33 changes: 4 additions & 29 deletions tests/vendor/test_esp_unspecified_reference_2294_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
from __future__ import annotations

import importlib.util
import pathlib
import unittest
from typing import TYPE_CHECKING

from tests._support import reimport_once_per_class
from tests.vendor._crawler import ROOT, import_from_checkout, make_crawler, normalize

if TYPE_CHECKING:
from typing import Any
Expand All @@ -28,9 +28,6 @@
#: with the committed file, which the vendor scripts regenerate on one interpreter.
__tier__ = 'LATEST'

#: Repository root, i.e. the grandparent of the directory holding this file.
ROOT = pathlib.Path(__file__).resolve().parents[2]

#: Every distribution importing :mod:`pcapkit.vendor` needs -- see
#: :mod:`tests.vendor.test_ipx_packet_unit` for why all three are checked.
VENDOR_DEPS = ('requests', 'bs4', 'html5lib')
Expand Down Expand Up @@ -62,31 +59,13 @@
)


def _normalize(context: 'str') -> 'str':
"""Apply the whitespace normalisation :meth:`Vendor.__init__` writes files through."""
lines = [] # type: list[str]
for line in context.splitlines():
if line:
if line.strip():
lines.append(line.rstrip())
else:
lines.append(line)
return '\n'.join(lines) + '\n'


@unittest.skipUnless(HAS_VENDOR_DEPS, f'vendor extra not installed ({", ".join(VENDOR_DEPS)})')
class UnspecifiedReferenceTests(unittest.TestCase):
"""A bracketed ``[UNSPECIFIED]`` cell renders as no citation at all."""

def setUp(self) -> None:
reimport_once_per_class(self)

import pcapkit.vendor.default as default

resolved = pathlib.Path(default.__file__).resolve()
if ROOT not in resolved.parents:
self.skipTest(f'{default.__name__} was imported from {resolved}, which is '
f'outside {ROOT}; install this checkout with `pip install -e .`')
import_from_checkout(self, 'pcapkit.vendor.default')

@staticmethod
def _crawlers() -> 'tuple[Any, ...]':
Expand Down Expand Up @@ -114,12 +93,8 @@ def test_rfcs_keeps_a_bracketed_citation(self) -> None:
def test_integrity_matches_the_committed_file(self) -> None:
from pcapkit.vendor.esp.integrity import Integrity

vendor = Integrity.__new__(Integrity)
vendor.NAME = Integrity.__name__
vendor.DOCS = Integrity.__doc__
lines = vendor.request(INTEGRITY_CSV)
vendor.record = vendor.count(lines)
rendered = _normalize(vendor.context(lines))
vendor, lines = make_crawler(Integrity, INTEGRITY_CSV)
rendered = normalize(vendor.context(lines))

path = ROOT / 'pcapkit' / 'const' / 'esp' / 'integrity.py'
committed = path.read_text(encoding='utf-8')
Expand Down
Loading
Loading