diff --git a/tests/const/test_const_enum_lookup.py b/tests/const/test_const_enum_lookup.py index 6952cf7931..05b3727686 100644 --- a/tests/const/test_const_enum_lookup.py +++ b/tests/const/test_const_enum_lookup.py @@ -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. @@ -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`. diff --git a/tests/vendor/_crawler.py b/tests/vendor/_crawler.py new file mode 100644 index 0000000000..4f08973264 --- /dev/null +++ b/tests/vendor/_crawler.py @@ -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__ ` 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 diff --git a/tests/vendor/test_crawler_reachability_unit.py b/tests/vendor/test_crawler_reachability_unit.py index d5ab1d192d..32746a7ad7 100644 --- a/tests/vendor/test_crawler_reachability_unit.py +++ b/tests/vendor/test_crawler_reachability_unit.py @@ -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 @@ -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 @@ -106,56 +103,8 @@ 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``. @@ -163,7 +112,8 @@ def _reachable_from(self, module: 'Any') -> 'dict[str, Any]': 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 @@ -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 @@ -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)) @@ -205,7 +155,7 @@ def test_every_crawler_is_reachable_from_its_own_protocol_target(self) -> None: # The `--target ` 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(): @@ -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__) diff --git a/tests/vendor/test_esp_unspecified_reference_2294_unit.py b/tests/vendor/test_esp_unspecified_reference_2294_unit.py index 6d33158f35..f2edb37bbb 100644 --- a/tests/vendor/test_esp_unspecified_reference_2294_unit.py +++ b/tests/vendor/test_esp_unspecified_reference_2294_unit.py @@ -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 @@ -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') @@ -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, ...]': @@ -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') diff --git a/tests/vendor/test_ftp_return_code_unit.py b/tests/vendor/test_ftp_return_code_unit.py index 7a291a027c..6a83361dbf 100644 --- a/tests/vendor/test_ftp_return_code_unit.py +++ b/tests/vendor/test_ftp_return_code_unit.py @@ -35,11 +35,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 import_from_checkout if TYPE_CHECKING: from typing import Any @@ -51,9 +51,6 @@ #: tests/vendor/test_vendor_variables_1726_unit.py. __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_user_agent_unit` for why ``requests`` alone is not #: enough. ``html5lib`` ships in the ``vendor`` extra (:file:`pyproject.toml`), @@ -113,18 +110,8 @@ class FTPReturnCodeEmptyRowTests(unittest.TestCase): def setUp(self) -> None: reimport_once_per_class(self) - - import pcapkit.vendor.ftp.return_code as vendor_module - - # The module has to come from this checkout, or the guard under test is - # not the one being exercised. An environment mismatch, hence a skip. - resolved = pathlib.Path(vendor_module.__file__).resolve() - if ROOT not in resolved.parents: - self.skipTest(f'{vendor_module.__name__} was imported from {resolved}, which is ' - f'outside {ROOT}; install this checkout with `pip install -e .` to run ' - f'this suite against it') - - self.vendor_module = vendor_module + # From this checkout, or the guard under test is not the one exercised. + self.vendor_module = import_from_checkout(self, 'pcapkit.vendor.ftp.return_code')[0] def _vendor(self) -> 'Any': """A crawler with the attributes ``__init__`` would have set. diff --git a/tests/vendor/test_ieee802_11_crawlers_2575_unit.py b/tests/vendor/test_ieee802_11_crawlers_2575_unit.py index 89451b74bf..1125738215 100644 --- a/tests/vendor/test_ieee802_11_crawlers_2575_unit.py +++ b/tests/vendor/test_ieee802_11_crawlers_2575_unit.py @@ -17,11 +17,11 @@ import importlib 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 @@ -30,9 +30,6 @@ #: it 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] - #: The distributions importing :mod:`pcapkit.vendor` with its crawlers needs, as #: ``test_ipx_packet_unit.py`` names them. VENDOR_DEPS = ('requests', 'bs4', 'html5lib') @@ -50,19 +47,6 @@ ) -def _normalize(context: 'str') -> 'str': - """Apply the whitespace normalisation the generator writes files through, - as ``test_ipx_packet_unit.py`` does.""" - 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 IEEE80211CrawlerTests(unittest.TestCase): """The hand-maintained Table 9-1 registries, and the crawlers that do not crawl.""" @@ -72,30 +56,15 @@ def setUp(self) -> None: def _crawler(self, module: 'str', name: 'str') -> 'Any': """The crawler module, skipping when it was imported from another tree.""" - vendor_module = importlib.import_module(f'pcapkit.vendor.ieee802_11.{module}') - const_module = importlib.import_module(f'pcapkit.const.ieee802_11.{module}') - for found in (vendor_module, const_module): - resolved = pathlib.Path(found.__file__).resolve() - if ROOT not in resolved.parents: - self.skipTest(f'{found.__name__} was imported from {resolved}, which is outside ' - f'{ROOT}; install this checkout with `pip install -e .`') + vendor_module, _ = import_from_checkout(self, f'pcapkit.vendor.ieee802_11.{module}', + f'pcapkit.const.ieee802_11.{module}') return getattr(vendor_module, name) - @staticmethod - def _vendor(klass: 'Any') -> 'Any': - """A crawler instance with the attributes ``__init__`` would set, without - the write ``__init__`` makes to the working tree.""" - vendor = klass.__new__(klass) - vendor.NAME = klass.__name__ - vendor.DOCS = klass.__doc__ - vendor.record = vendor.count(vendor.request()) - return vendor - def test_regeneration_reproduces_the_committed_constant_files(self) -> None: for module, name in CRAWLERS: with self.subTest(crawler=name): - vendor = self._vendor(self._crawler(module, name)) - generated = _normalize(vendor.context(vendor.request())) + vendor, data = make_crawler(self._crawler(module, name)) + generated = normalize(vendor.context(data)) path = ROOT / 'pcapkit' / 'const' / 'ieee802_11' / f'{module}.py' self.assertEqual(generated, path.read_text(encoding='utf-8'), f'regenerating {path.relative_to(ROOT)} would change it; run ' @@ -106,7 +75,7 @@ def test_no_crawler_has_a_link(self) -> None: with self.subTest(crawler=name): klass = self._crawler(module, name) self.assertIsNone(klass.LINK) - self.assertIs(self._vendor(klass)._request(), # pylint: disable=protected-access + self.assertIs(make_crawler(klass)[0]._request(), # pylint: disable=protected-access importlib.import_module(klass.__module__).DATA) def test_every_subtype_value_resolves(self) -> None: diff --git a/tests/vendor/test_ipx_packet_unit.py b/tests/vendor/test_ipx_packet_unit.py index 0c71edb3ff..2829a64f3a 100644 --- a/tests/vendor/test_ipx_packet_unit.py +++ b/tests/vendor/test_ipx_packet_unit.py @@ -31,11 +31,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 @@ -44,9 +44,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` with its crawlers needs. #: ``pcapkit.vendor.default`` imports ``requests`` at module scope, and several #: crawlers ``import bs4`` at module scope. Without either, the ``pcapkit.vendor`` @@ -84,33 +81,6 @@ ) -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`. - - 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' - - @unittest.skipUnless(HAS_VENDOR_DEPS, f'vendor extra not installed ({", ".join(VENDOR_DEPS)})') class IPXPacketVendorTests(unittest.TestCase): """The hand-maintained registry, and the crawler that does not crawl.""" @@ -121,39 +91,12 @@ class IPXPacketVendorTests(unittest.TestCase): def setUp(self) -> None: reimport_once_per_class(self) - - import pcapkit.const.ipx.packet as const_module - import pcapkit.vendor.ipx.packet as vendor_module - - # Both modules have to come from this checkout for any of the comparisons - # below to mean anything: the generated text is compared against this - # repository's constant file, so a vendor module imported from an - # installed copy elsewhere would be comparing two trees. That is an - # environment mismatch rather than a defect, hence a skip. - for module in (vendor_module, const_module): - resolved = pathlib.Path(module.__file__).resolve() - if ROOT not in resolved.parents: - self.skipTest(f'{module.__name__} was imported from {resolved}, which is outside ' - f'{ROOT}; install this checkout with `pip install -e .` to run this ' - f'suite against it') - - self.vendor_module = vendor_module - self.const_module = const_module + self.vendor_module, self.const_module = import_from_checkout( + self, 'pcapkit.vendor.ipx.packet', 'pcapkit.const.ipx.packet') def _vendor(self) -> 'Any': - """A crawler instance with the attributes ``__init__`` would have set. - - ``Vendor.__init__`` regenerates and *writes* the constant file as a side - effect of construction, which a test has no business doing to the working - tree, so the four attributes it sets are set here instead. - - """ - vendor = self.vendor_module.Packet.__new__(self.vendor_module.Packet) - vendor.NAME = self.vendor_module.Packet.__name__ - vendor.DOCS = self.vendor_module.Packet.__doc__ - data = vendor.request() - vendor.record = vendor.count(data) - return vendor + """A crawler instance with the attributes ``__init__`` would have set.""" + return make_crawler(self.vendor_module.Packet)[0] def test_link_is_none_so_nothing_is_fetched(self) -> None: # No LINK, stated as an assertion: Vendor._request() short-circuits to @@ -184,7 +127,7 @@ def test_regeneration_reproduces_the_committed_constant_file(self) -> None: # crawler must be a no-op against what is checked in, so an edit to DATA # that was never regenerated shows up here. vendor = self._vendor() - generated = _normalize(vendor.context(vendor.request())) + generated = normalize(vendor.context(vendor.request())) committed = (ROOT / 'pcapkit' / 'const' / 'ipx' / 'packet.py').read_text(encoding='utf-8') self.assertEqual(generated, committed, 'regenerating pcapkit/const/ipx/packet.py would change it; run ' diff --git a/tests/vendor/test_ipx_socket_unit.py b/tests/vendor/test_ipx_socket_unit.py index 53d59603f2..ad5c837e1a 100644 --- a/tests/vendor/test_ipx_socket_unit.py +++ b/tests/vendor/test_ipx_socket_unit.py @@ -25,11 +25,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 @@ -38,9 +38,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] - #: Whether the crawler machinery is importable at all. ``pcapkit.vendor.default`` #: imports :mod:`requests` at module scope, and :mod:`pcapkit.vendor` imports its #: crawlers, several of which import :mod:`bs4` at module scope, only when @@ -142,33 +139,6 @@ } -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`. - - 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' - - @unittest.skipUnless(HAS_CRAWLER_DEPS, 'requests and/or beautifulsoup4 not installed') class IPXSocketVendorTests(unittest.TestCase): """The hand-maintained registry, and the crawler that does not crawl.""" @@ -179,40 +149,12 @@ class IPXSocketVendorTests(unittest.TestCase): def setUp(self) -> None: reimport_once_per_class(self) - - import pcapkit.const.ipx.socket as const_module - import pcapkit.vendor.ipx.socket as vendor_module - - # Both modules have to come from this checkout for any of the - # comparisons below to mean anything: the generated text is compared - # against this repository's constant file, so a vendor module imported - # from an installed copy elsewhere would be comparing two trees. That is - # an environment mismatch rather than a defect, hence a skip. - for module in (vendor_module, const_module): - resolved = pathlib.Path(module.__file__).resolve() - if ROOT not in resolved.parents: - self.skipTest(f'{module.__name__} was imported from {resolved}, which is outside ' - f'{ROOT}; install this checkout with `pip install -e .` to run this ' - f'suite against it') - - self.vendor_module = vendor_module - self.const_module = const_module + self.vendor_module, self.const_module = import_from_checkout( + self, 'pcapkit.vendor.ipx.socket', 'pcapkit.const.ipx.socket') def _vendor(self) -> 'Any': - """A crawler instance with the attributes ``__init__`` would have set. - - ``Vendor.__init__`` regenerates and *writes* the constant file as a side - effect of construction, which a test has no business doing to the - working tree, so the attributes it sets -- ``NAME``, ``DOCS`` and - ``record`` -- are set here instead. - - """ - vendor = self.vendor_module.Socket.__new__(self.vendor_module.Socket) - vendor.NAME = self.vendor_module.Socket.__name__ - vendor.DOCS = self.vendor_module.Socket.__doc__ - data = vendor.request() - vendor.record = vendor.count(data) - return vendor + """A crawler instance with the attributes ``__init__`` would have set.""" + return make_crawler(self.vendor_module.Socket)[0] def test_link_is_none_so_nothing_is_fetched(self) -> None: # No LINK, stated as an assertion: Vendor._request() short-circuits to @@ -243,7 +185,7 @@ def test_regeneration_reproduces_the_committed_constant_file(self) -> None: # the crawler must be a no-op against what is checked in, so an edit to # DATA that was never regenerated shows up here. vendor = self._vendor() - generated = _normalize(vendor.context(vendor.request())) + generated = normalize(vendor.context(vendor.request())) committed = (ROOT / 'pcapkit' / 'const' / 'ipx' / 'socket.py').read_text(encoding='utf-8') self.assertEqual(generated, committed, 'regenerating pcapkit/const/ipx/socket.py would change it; run ' diff --git a/tests/vendor/test_radiotap_crawler_2576_unit.py b/tests/vendor/test_radiotap_crawler_2576_unit.py index 74d3bb3b9a..d799479a6b 100644 --- a/tests/vendor/test_radiotap_crawler_2576_unit.py +++ b/tests/vendor/test_radiotap_crawler_2576_unit.py @@ -21,11 +21,11 @@ import html import importlib 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, normalize if TYPE_CHECKING: from typing import Any @@ -34,9 +34,6 @@ #: with the committed files, 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] - #: The distributions importing :mod:`pcapkit.vendor` with its crawlers needs, as #: ``test_ipx_packet_unit.py`` names them. VENDOR_DEPS = ('requests', 'bs4', 'html5lib') @@ -433,19 +430,6 @@ def _page(name: 'str') -> 'str': return ''.join(parts) -def _normalize(context: 'str') -> 'str': - """Apply the whitespace normalisation the generator writes files through, - as ``test_ipx_packet_unit.py`` does.""" - 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 RadiotapCrawlerTests(unittest.TestCase): """The scraped radiotap.org tables, and the registries they generate.""" @@ -455,13 +439,8 @@ def setUp(self) -> None: def _crawler(self, module: 'str', name: 'str') -> 'Any': """The crawler class, skipping when it was imported from another tree.""" - vendor_module = importlib.import_module(f'pcapkit.vendor.radiotap.{module}') - const_module = importlib.import_module(f'pcapkit.const.radiotap.{module}') - for found in (vendor_module, const_module): - resolved = pathlib.Path(found.__file__).resolve() - if ROOT not in resolved.parents: - self.skipTest(f'{found.__name__} was imported from {resolved}, which is outside ' - f'{ROOT}; install this checkout with `pip install -e .`') + vendor_module, _ = import_from_checkout(self, f'pcapkit.vendor.radiotap.{module}', + f'pcapkit.const.radiotap.{module}') return getattr(vendor_module, name) def _assert_regenerates(self, module: 'str', name: 'str', *pages: 'str') -> None: @@ -472,7 +451,7 @@ def _assert_regenerates(self, module: 'str', name: 'str', *pages: 'str') -> None vendor.DOCS = klass.__doc__ data = [item for page in pages for item in vendor.request(page)] vendor.record = vendor.count(data) - generated = _normalize(vendor.context(data)) + generated = normalize(vendor.context(data)) path = ROOT / 'pcapkit' / 'const' / 'radiotap' / f'{module}.py' self.assertEqual(generated, path.read_text(encoding='utf-8'), f'regenerating {path.relative_to(ROOT)} would change it; run ' diff --git a/tests/vendor/test_radiotap_crawler_2647_unit.py b/tests/vendor/test_radiotap_crawler_2647_unit.py index ade87944d4..e4feff1cbf 100644 --- a/tests/vendor/test_radiotap_crawler_2647_unit.py +++ b/tests/vendor/test_radiotap_crawler_2647_unit.py @@ -23,11 +23,11 @@ import html import importlib 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 @@ -36,9 +36,6 @@ #: with the committed files, 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] - #: The distributions importing :mod:`pcapkit.vendor` with its crawlers needs. VENDOR_DEPS = ('requests', 'bs4', 'html5lib') @@ -142,18 +139,6 @@ def _page(name: 'str') -> 'str': return ''.join(parts) -def _normalize(context: 'str') -> 'str': - """Apply the whitespace normalisation the generator 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 RadiotapMixedBitmapCrawlerTests(unittest.TestCase): """The known-bit registries of the mixed bitmaps, and their crawlers.""" @@ -163,13 +148,8 @@ def setUp(self) -> None: def _crawler(self, module: 'str', name: 'str') -> 'Any': """The crawler class, skipping when it was imported from another tree.""" - vendor_module = importlib.import_module(f'pcapkit.vendor.radiotap.{module}') - const_module = importlib.import_module(f'pcapkit.const.radiotap.{module}') - for found in (vendor_module, const_module): - resolved = pathlib.Path(found.__file__).resolve() - if ROOT not in resolved.parents: - self.skipTest(f'{found.__name__} was imported from {resolved}, which is outside ' - f'{ROOT}; install this checkout with `pip install -e .`') + vendor_module, _ = import_from_checkout(self, f'pcapkit.vendor.radiotap.{module}', + f'pcapkit.const.radiotap.{module}') return getattr(vendor_module, name) def test_the_registries_regenerate(self) -> None: @@ -177,13 +157,9 @@ def test_the_registries_regenerate(self) -> None: for module, name, page, _, _ in CRAWLERS: with self.subTest(crawler=name): klass = self._crawler(module, name) - vendor = klass.__new__(klass) - vendor.NAME = klass.__name__ - vendor.DOCS = klass.__doc__ - data = vendor.request(_page(page)) - vendor.record = vendor.count(data) + vendor, data = make_crawler(klass, _page(page)) path = ROOT / 'pcapkit' / 'const' / 'radiotap' / f'{module}.py' - self.assertEqual(_normalize(vendor.context(data)), path.read_text(encoding='utf-8'), + self.assertEqual(normalize(vendor.context(data)), path.read_text(encoding='utf-8'), f'regenerating {path.relative_to(ROOT)} would change it; run ' '`pcapkit-vendor radiotap` and commit the result') diff --git a/tests/vendor/test_vendor_dest_path_unit.py b/tests/vendor/test_vendor_dest_path_unit.py index 1c4db8b147..acf68c34c9 100644 --- a/tests/vendor/test_vendor_dest_path_unit.py +++ b/tests/vendor/test_vendor_dest_path_unit.py @@ -89,12 +89,10 @@ """ from __future__ import annotations -import importlib import importlib.util import inspect import os import pathlib -import pkgutil import sys import tempfile import textwrap @@ -103,6 +101,7 @@ from unittest import mock from tests._support import reimport_once_per_class +from tests.vendor._crawler import defined_crawlers, import_from_checkout if TYPE_CHECKING: from typing import Any @@ -114,9 +113,6 @@ #: tests/vendor/test_vendor_variables_1726_unit.py. __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, for the reason the #: module docstring above gives. Deliberately just the two #: :file:`tests/vendor/test_crawler_reachability_unit.py` uses -- not the @@ -182,49 +178,11 @@ class ExistingCrawlerDestPathTests(unittest.TestCase): def setUp(self) -> None: reimport_once_per_class(self) - - import pcapkit - import pcapkit.vendor as vendor - from pcapkit.vendor.default import Vendor - - # Comparing this checkout's crawlers against this checkout's __file__ - # only means something if pcapkit was imported from here -- - # see test_crawler_reachability_unit.py's setUp for the same guard. - 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': - return isinstance(obj, type) and issubclass(obj, self.Vendor) and obj is not self.Vendor - - def _defined_crawlers(self) -> 'dict[str, Any]': - """Every crawler class defined under :file:`pcapkit/vendor/`. - - Discovered from the filesystem with :func:`pkgutil.walk_packages`, the - same approach :file:`tests/vendor/test_crawler_reachability_unit.py` - uses -- this file is not about ``__all__`` reachability, but the - discovery itself is identical, and reusing it means the enumeration - here covers exactly what that suite calls "defined". - - """ - 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 test_every_crawler_resolves_to_its_existing_const_file(self) -> None: - crawlers = self._defined_crawlers() + crawlers = defined_crawlers(self.vendor, self.Vendor) # A suite that silently discovered zero crawlers would report success # having checked nothing -- fail loudly instead if discovery itself broke. self.assertGreater(len(crawlers), 0, 'no crawlers were discovered under pcapkit.vendor') @@ -270,22 +228,10 @@ class NestedCrawlerDestPathTests(unittest.TestCase): def setUp(self) -> None: reimport_once_per_class(self) - - import pcapkit - import pcapkit.vendor as vendor - import pcapkit.vendor.default as default - from pcapkit.utilities.exceptions import VendorPathNotFound - - 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 = default.Vendor - self.default = default - self.VendorPathNotFound = VendorPathNotFound + self.vendor, self.default, exceptions = import_from_checkout( + self, 'pcapkit.vendor', 'pcapkit.vendor.default', 'pcapkit.utilities.exceptions') + self.Vendor = self.default.Vendor + self.VendorPathNotFound = exceptions.VendorPathNotFound self._tempdir = tempfile.TemporaryDirectory(prefix='pcapkit-vendor-nested-test-') self.addCleanup(self._tempdir.cleanup) diff --git a/tests/vendor/test_vendor_ipv6_extension_header_925_unit.py b/tests/vendor/test_vendor_ipv6_extension_header_925_unit.py index a09792aa35..b36a1dfb3b 100644 --- a/tests/vendor/test_vendor_ipv6_extension_header_925_unit.py +++ b/tests/vendor/test_vendor_ipv6_extension_header_925_unit.py @@ -54,12 +54,12 @@ from __future__ import annotations import importlib.util -import pathlib import re 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 @@ -68,9 +68,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 #: rather than only :mod:`requests`. @@ -162,29 +159,6 @@ def _comment_from_enum(enum: 'list[str]', name: 'str') -> 'str': raise AssertionError(f'no enum entry named {name!r}') -def _normalize(context: 'str') -> 'str': - """Apply the whitespace normalisation :meth:`Vendor.__init__` writes files - through, so a byte comparison against the committed file does the same - the generator itself would have -- see - :mod:`tests.vendor.test_ipx_packet_unit` for the same helper. - - Args: - context: Return value of :meth:`~pcapkit.vendor.default.Vendor.context`. - - 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' - - @unittest.skipUnless(HAS_VENDOR_DEPS, f'vendor extra not installed ({", ".join(VENDOR_DEPS)})') class ExtensionHeaderVendorTests(unittest.TestCase): """The crawler: authoritative registry, 3-column parser, names preserved.""" @@ -194,30 +168,11 @@ class ExtensionHeaderVendorTests(unittest.TestCase): def setUp(self) -> None: reimport_once_per_class(self) + self.vendor_module = import_from_checkout(self, 'pcapkit.vendor.ipv6.extension_header')[0] - import pcapkit.vendor.ipv6.extension_header as vendor_module - - resolved = pathlib.Path(vendor_module.__file__).resolve() - if ROOT not in resolved.parents: - self.skipTest(f'{vendor_module.__name__} was imported from {resolved}, which is ' - f'outside {ROOT}; install this checkout with `pip install -e .` to ' - f'run this suite against it') - - self.vendor_module = vendor_module - - def _vendor(self) -> 'Any': - """A crawler instance with the attributes ``__init__`` would have set, - but without ``__init__``'s network fetch and file write -- see - :mod:`tests.vendor.test_ipx_packet_unit` for the same technique. - - """ - cls = self.vendor_module.ExtensionHeader - vendor = cls.__new__(cls) - vendor.NAME = cls.__name__ - vendor.DOCS = cls.__doc__ - lines = vendor.request(FIXTURE_CSV) - vendor.record = vendor.count(lines) - return vendor, lines + def _vendor(self) -> 'tuple[Any, list[str]]': + """The crawler set up from :data:`FIXTURE_CSV`, and the lines it split.""" + return make_crawler(self.vendor_module.ExtensionHeader, FIXTURE_CSV) def test_link_points_at_the_authoritative_registry(self) -> None: # The root cause, stated as an assertion: the authoritative registry, @@ -318,7 +273,7 @@ def test_context_matches_the_committed_const_file_byte_for_byte(self) -> None: # not prove the *live* registry still matches FIXTURE_CSV -- only # that the committed file is exactly what this fixture produces. vendor, lines = self._vendor() - generated = _normalize(vendor.context(lines)) + generated = normalize(vendor.context(lines)) committed = (ROOT / 'pcapkit' / 'const' / 'ipv6' / 'extension_header.py').read_text(encoding='utf-8') self.assertEqual(generated, committed, 'pcapkit/const/ipv6/extension_header.py no longer matches what ' diff --git a/tests/vendor/test_vendor_mh_lla_code_1848_unit.py b/tests/vendor/test_vendor_mh_lla_code_1848_unit.py index cf3185adcf..f3dc28e583 100644 --- a/tests/vendor/test_vendor_mh_lla_code_1848_unit.py +++ b/tests/vendor/test_vendor_mh_lla_code_1848_unit.py @@ -13,11 +13,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 @@ -26,9 +26,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] - #: The committed module the crawler generates. CONST = ROOT / 'pcapkit' / 'const' / 'mh' / 'lla_code.py' @@ -40,26 +37,6 @@ HAS_VENDOR_DEPS = all(importlib.util.find_spec(name) is not None for name in VENDOR_DEPS) -def _normalize(context: 'str') -> 'str': - """Apply the whitespace normalisation :meth:`Vendor.__init__` writes with. - - Args: - context: Return value of :meth:`~pcapkit.vendor.default.Vendor.context`. - - 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' - - @unittest.skipUnless(HAS_VENDOR_DEPS, f'vendor extra not installed ({", ".join(VENDOR_DEPS)})') class LLACodeVendorTests(unittest.TestCase): """The hand-written table and its template, rendered without a write.""" @@ -69,26 +46,11 @@ class LLACodeVendorTests(unittest.TestCase): def setUp(self) -> 'None': reimport_once_per_class(self) - - import pcapkit.vendor.mh.lla_code as vendor_module - - resolved = pathlib.Path(vendor_module.__file__).resolve() - if ROOT not in resolved.parents: - self.skipTest(f'{vendor_module.__name__} was imported from {resolved}, which is ' - f'outside {ROOT}; install this checkout with `pip install -e .` to ' - f'run this suite against it') - - self.vendor_module = vendor_module + self.vendor_module = import_from_checkout(self, 'pcapkit.vendor.mh.lla_code')[0] def _vendor(self) -> 'tuple[Any, dict[int, str]]': """A crawler with the attributes ``__init__`` sets, but none of its I/O.""" - cls = self.vendor_module.LLACode - vendor = cls.__new__(cls) - vendor.NAME = cls.__name__ - vendor.DOCS = cls.__doc__ - data = vendor.request() - vendor.record = vendor.count(data) - return vendor, data + return make_crawler(self.vendor_module.LLACode) def test_the_table_carries_the_rfc_names(self) -> 'None': vendor, data = self._vendor() @@ -114,7 +76,7 @@ def test_context_renders_no_version_directive(self) -> 'None': def test_context_matches_the_committed_const_file_byte_for_byte(self) -> 'None': vendor, data = self._vendor() - rendered = _normalize(vendor.context(data)) + rendered = normalize(vendor.context(data)) self.assertEqual(rendered, CONST.read_text(encoding='utf-8')) diff --git a/tests/vendor/test_vendor_reference_formats_1664_unit.py b/tests/vendor/test_vendor_reference_formats_1664_unit.py index ead4574b04..2e2beda01d 100644 --- a/tests/vendor/test_vendor_reference_formats_1664_unit.py +++ b/tests/vendor/test_vendor_reference_formats_1664_unit.py @@ -21,11 +21,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 @@ -34,9 +34,6 @@ #: with the committed files, 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') @@ -191,48 +188,20 @@ TLS_LABEL_NEW = TLS_LABEL_OLD.replace('[RFC', '[RFC ') -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 ReferenceFormatTests(unittest.TestCase): """Both of IANA's reference spellings render the same const file.""" 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 .`') - - @staticmethod - def _vendor(cls: 'Any', text: 'str') -> 'tuple[Any, list[str]]': - """A crawler as ``__init__`` would set it up, without the fetch and the write.""" - vendor = cls.__new__(cls) - vendor.NAME = cls.__name__ - vendor.DOCS = cls.__doc__ - lines = vendor.request(text) - vendor.record = vendor.count(lines) - return vendor, lines + import_from_checkout(self, 'pcapkit.vendor.default') def _context(self, cls: 'Any', text: 'str') -> 'str': - vendor, lines = self._vendor(cls, text) - return _normalize(vendor.context(lines)) + vendor, lines = make_crawler(cls, text) + return normalize(vendor.context(lines)) def _comments(self, cls: 'Any', text: 'str') -> 'list[str]': - vendor, lines = self._vendor(cls, text) + vendor, lines = make_crawler(cls, text) enum, _ = vendor.process(lines) return [entry.split('\n ', 1)[0] for entry in enum] @@ -326,7 +295,7 @@ def test_apptype_renders_both_alike(self) -> None: cells = {} for text in (APPTYPE_OLD, APPTYPE_NEW): - vendor, lines = self._vendor(AppType, text) + vendor, lines = make_crawler(AppType, text) line, _ = vendor.records(lines) cells[text] = {name: record.cells for name, record in line.items()} self.assertEqual(cells[APPTYPE_NEW], cells[APPTYPE_OLD])