pax_global_header00006660000000000000000000000064143111450340014506gustar00rootroot0000000000000052 comment=9a543e120929e9068acffb56e440f6fe5542ddf8 colcon-python-setup-py-0.2.8/000077500000000000000000000000001431114503400160755ustar00rootroot00000000000000colcon-python-setup-py-0.2.8/.github/000077500000000000000000000000001431114503400174355ustar00rootroot00000000000000colcon-python-setup-py-0.2.8/.github/workflows/000077500000000000000000000000001431114503400214725ustar00rootroot00000000000000colcon-python-setup-py-0.2.8/.github/workflows/ci.yaml000066400000000000000000000012071431114503400227510ustar00rootroot00000000000000name: Run tests on: push: branches: ['master'] pull_request: jobs: setup: runs-on: ubuntu-latest outputs: strategy: ${{steps.load.outputs.strategy}} steps: - uses: actions/checkout@v2 with: repository: colcon/ci - id: load run: echo "::set-output name=strategy::$(echo $(cat strategy.json))" pytest: needs: [setup] strategy: ${{fromJson(needs.setup.outputs.strategy)}} runs-on: ${{matrix.os}} steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: ${{matrix.python}} - uses: colcon/ci@v1 colcon-python-setup-py-0.2.8/LICENSE000066400000000000000000000261361431114503400171120ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. colcon-python-setup-py-0.2.8/README.rst000066400000000000000000000004471431114503400175710ustar00rootroot00000000000000colcon-python-setup-py ====================== An extension for `colcon-core `_ to identify packages with a ``setup.py`` file by introspecting the arguments to the ``setup()`` function call of `setuptools `_. colcon-python-setup-py-0.2.8/colcon_python_setup_py/000077500000000000000000000000001431114503400227035ustar00rootroot00000000000000colcon-python-setup-py-0.2.8/colcon_python_setup_py/__init__.py000066400000000000000000000001521431114503400250120ustar00rootroot00000000000000# Copyright 2016-2020 Dirk Thomas # Licensed under the Apache License, Version 2.0 __version__ = '0.2.8' colcon-python-setup-py-0.2.8/colcon_python_setup_py/package_augmentation/000077500000000000000000000000001431114503400270515ustar00rootroot00000000000000colcon-python-setup-py-0.2.8/colcon_python_setup_py/package_augmentation/__init__.py000066400000000000000000000000001431114503400311500ustar00rootroot00000000000000colcon-python-setup-py-0.2.8/colcon_python_setup_py/package_augmentation/python_setup_py.py000066400000000000000000000034341431114503400327000ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from colcon_core.package_augmentation \ import PackageAugmentationExtensionPoint from colcon_core.package_augmentation.python import \ create_dependency_descriptor from colcon_core.plugin_system import satisfies_version from colcon_python_setup_py.package_identification.python_setup_py import \ get_setup_information class PythonPackageAugmentation(PackageAugmentationExtensionPoint): """Augment Python packages with information from `setup.py` files.""" # the priority needs to be lower than the extensions augmenting packages # using the setup.cfg file PRIORITY = 90 def __init__(self): # noqa: D107 super().__init__() satisfies_version( PackageAugmentationExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def augment_package( # noqa: D102 self, desc, *, additional_argument_names=None ): if desc.type != 'python': return if 'get_python_setup_options' in desc.metadata: return setup_py = desc.path / 'setup.py' if not setup_py.is_file(): return config = get_setup_information(setup_py) for dependency_type, option_name in [ ('build', 'setup_requires'), ('run', 'install_requires'), ('test', 'tests_require') ]: desc.dependencies[dependency_type] = { create_dependency_descriptor(d) for d in config[option_name] or ()} def getter(env): nonlocal setup_py return get_setup_information(setup_py, env=env) desc.metadata['get_python_setup_options'] = getter desc.metadata['version'] = config['metadata'].get('version') colcon-python-setup-py-0.2.8/colcon_python_setup_py/package_identification/000077500000000000000000000000001431114503400273475ustar00rootroot00000000000000colcon-python-setup-py-0.2.8/colcon_python_setup_py/package_identification/__init__.py000066400000000000000000000000001431114503400314460ustar00rootroot00000000000000colcon-python-setup-py-0.2.8/colcon_python_setup_py/package_identification/python_setup_py.py000066400000000000000000000245271431114503400332040ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import ast from contextlib import suppress with suppress(ImportError): # needed before importing distutils # to avoid warning introduced in setuptools 49.2.0 import setuptools import distutils.core import os from pathlib import Path import runpy import subprocess import sys from threading import Lock import warnings from colcon_core.package_identification import logger from colcon_core.package_identification \ import PackageIdentificationExtensionPoint from colcon_core.package_identification.python import \ create_dependency_descriptor from colcon_core.plugin_system import satisfies_version class PythonPackageIdentification(PackageIdentificationExtensionPoint): """Identify Python packages with `setup.py` files.""" # the priority needs to be lower than the extensions identifying packages # using the setup.cfg file PRIORITY = 90 def __init__(self): # noqa: D107 super().__init__() satisfies_version( PackageIdentificationExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def identify(self, desc): # noqa: D102 if desc.type is not None and desc.type != 'python': return setup_py = desc.path / 'setup.py' if not setup_py.is_file(): return config = get_setup_information(setup_py) desc.type = 'python' name = config['metadata'].get('name') if not name: logger.error( 'Failed to determine Python package name in ' "'{setup_py.parent}'".format_map(locals())) raise RuntimeError( 'Failed to determine Python package name in ' "'{setup_py.parent}'".format_map(locals())) if desc.name is not None and desc.name != name: logger.error('Package name already set to different value') raise RuntimeError('Package name already set to different value') desc.name = name cwd_lock = None def get_setup_arguments(setup_py): """ Capture the arguments of the setup() function in the setup.py file. The function is being run within the current Python interpreter. Therefore the processed setup.py file can not have any additional dependencies not available in the current environment. :param setup_py: the path to the setup.py file :returns: a dictionary containing the arguments of the setup() function :rtype: dict """ warnings.warn( 'colcon_python_setup_py.package_identification.python_setup_py.' 'get_setup_arguments() has been deprecated, use ' 'colcon_python_setup_py.package_identification.python_setup_py.' 'get_setup_information() instead', stacklevel=2) global cwd_lock if not cwd_lock: cwd_lock = Lock() setup_py = Path(str(setup_py)).resolve() assert setup_py.name == 'setup.py' # prevent side effects in other threads with cwd_lock: # change to the directory containing the setup.py file old_cwd = os.getcwd() os.chdir(str(setup_py.parent)) try: data = {} mock_setup = create_mock_setup_function(data) # replace setup() function of distutils and setuptools # in order to capture its arguments try: distutils_setup = distutils.core.setup distutils.core.setup = mock_setup with suppress(NameError): setuptools_setup = setuptools.setup setuptools.setup = mock_setup # evaluate the setup.py file runpy.run_path(str(setup_py)) finally: distutils.core.setup = distutils_setup with suppress(NameError): setuptools.setup = setuptools_setup # filter out any data which doesn't work with ast.literal_eval for key, value in list(data.items()): try: ast.literal_eval(repr(value)) except SyntaxError: del data[key] return data finally: os.chdir(old_cwd) def create_mock_setup_function(data): """ Create a mock function to capture its arguments. It can replace either distutils.core.setup or setuptools.setup. :param data: a dictionary which is updated with the captured arguments :returns: a function to replace distutils.core.setup and setuptools.setup :rtype: callable """ warnings.warn( 'colcon_python_setup_py.package_identification.python_setup_py.' 'create_mock_setup_function() will be removed in the future', DeprecationWarning, stacklevel=2) def setup(*args, **kwargs): if args: raise RuntimeError( 'setup() function invoked with positional arguments') data.update(kwargs) return setup def extract_data(**kwargs): """ Extract information from known keyword arguments to the setup function. The `name` attribute is required and returned under the `name` key. The following dependencies are stripped of their version specifier. The `setup_requires` items are returned as `build_depends`. The `install_requires` items are returned as `run_depends`. The `tests_require` items are returned as `test_depends`. :param dict kwargs: The keywords :rtype: dict :raises RuntimeError: if the keywords don't contain `name` """ warnings.warn( 'colcon_python_setup_py.package_identification.python_setup_py.' 'extract_data() will be removed in the future', DeprecationWarning, stacklevel=2) if 'name' not in kwargs: raise RuntimeError( "setup() function invoked without the keyword argument 'name'") data = {'name': kwargs['name']} mapping = { 'setup_requires': 'build_depends', 'install_requires': 'run_depends', 'tests_require': 'test_depends', } for keyword, key in mapping.items(): data[key] = set() for dep in kwargs.get(keyword, []): descriptor = create_dependency_descriptor(dep) data[key].add(descriptor) return data def get_setup_arguments_with_context(setup_py, env): """ Capture the arguments of the setup() function in the setup.py file. To provide a custom environment when introspecting the setup() function a separate Python interpreter is being used which can have an extended PYTHONPATH etc. This function has been deprecated, use get_setup_information() instead. :param setup_py: The path of the setup.py file :param dict env: The environment variables to use when invoking the file :returns: a dictionary containing the arguments of the setup() function :rtype: dict """ pkg_path = Path(__file__).parents[3] if sys.platform == 'win32': pkg_path = str(pkg_path).replace(os.sep, os.altsep) setup_py = str(setup_py).replace(os.sep, os.altsep) code_lines = [ 'import sys', "sys.path.insert(0, '%s')" % pkg_path, 'from colcon_python_setup_py.package_identification.python_setup_py' ' import get_setup_arguments', "output = repr(get_setup_arguments('%s'))" % setup_py, "sys.stdout.buffer.write(output.encode('utf-8'))"] # invoke get_setup_arguments() in a separate interpreter cmd = [sys.executable, '-c', ';'.join(code_lines)] result = subprocess.run( cmd, stdout=subprocess.PIPE, env=env, check=True) output = result.stdout.decode('utf-8') return ast.literal_eval(output) _setup_information_cache = {} def get_setup_information(setup_py, *, env=None): """ Dry run the setup.py file and get the configuration information. A repeated invocation with the same arguments returns a cached result. :param Path setup_py: path to a setup.py script :param dict env: environment variables to set before running setup.py :return: dictionary of data describing the package. :raise: RuntimeError if the setup script encountered an error """ global _setup_information_cache if env is None: env = os.environ hashable_env = (setup_py, ) + tuple(sorted(env.items())) if hashable_env not in _setup_information_cache: _setup_information_cache[hashable_env] = _get_setup_information( setup_py, env=env) return _setup_information_cache[hashable_env] def _get_setup_information(setup_py, *, env=None): code_lines = [ 'import sys', # setuptools needs to be imported before distutils # to avoid warning introduced in setuptools 49.2.0 'from contextlib import suppress', 'exec("with suppress(ImportError):' ' from setuptools.extern.packaging.specifiers' ' import SpecifierSet")', # newer versions expose 'packaging' directly # on Arch 'extern' isn't part of the package 'exec("with suppress(ImportError):' ' from packaging.specifiers import SpecifierSet")', 'from distutils.core import run_setup', 'dist = run_setup(' " 'setup.py', script_args=('--dry-run',), stop_after='config')", "skip_keys = ('cmdclass', 'distclass', 'ext_modules', 'metadata')", 'data = {' ' key: value for key, value in dist.__dict__.items() ' ' if (' # skip private properties " not key.startswith('_') and " # skip methods ' not callable(value) and ' # skip objects whose representation can't be evaluated ' key not in skip_keys and ' # skip display options since they have no value, using metadata instead ' key not in dist.display_option_names' ' )' '}', "data['metadata'] = {" ' k: v for k, v in dist.metadata.__dict__.items() ' # skip values with custom type OrderedSet " if k not in ('license_files', 'provides_extras')}", "sys.stdout.buffer.write(repr(data).encode('utf-8'))"] # invoke distutils.core.run_setup() in a separate interpreter cmd = [ sys.executable, '-c', ';'.join(line.lstrip() for line in code_lines)] result = subprocess.run( cmd, stdout=subprocess.PIPE, cwd=os.path.abspath(str(setup_py.parent)), check=True, env=env) output = result.stdout.decode('utf-8') return ast.literal_eval(output) colcon-python-setup-py-0.2.8/publish-python.yaml000066400000000000000000000005561431114503400217540ustar00rootroot00000000000000artifacts: - type: wheel uploads: - type: pypi - type: stdeb uploads: - type: packagecloud config: repository: dirk-thomas/colcon distributions: - ubuntu:bionic - ubuntu:focal - ubuntu:jammy - debian:stretch - debian:buster - debian:bullseye colcon-python-setup-py-0.2.8/setup.cfg000066400000000000000000000041351431114503400177210ustar00rootroot00000000000000[metadata] name = colcon-python-setup-py version = attr: colcon_python_setup_py.__version__ url = https://colcon.readthedocs.io project_urls = Changelog = https://github.com/colcon/colcon-python-setup-py/milestones?direction=desc&sort=due_date&state=closed GitHub = https://github.com/colcon/colcon-python-setup-py/ author = Dirk Thomas author_email = web@dirk-thomas.net maintainer = Dirk Thomas maintainer_email = web@dirk-thomas.net classifiers = Development Status :: 3 - Alpha Environment :: Plugins Intended Audience :: Developers License :: OSI Approved :: Apache Software License Operating System :: MacOS Operating System :: Microsoft :: Windows Operating System :: POSIX Programming Language :: Python Topic :: Software Development :: Build Tools license = Apache License, Version 2.0 description = Extension for colcon to support Python packages with the metadata in the setup.py file. long_description = file: README.rst keywords = colcon [options] install_requires = colcon-core>=0.6.1 setuptools packages = find: zip_safe = true [options.extras_require] test = flake8>=3.6.0 flake8-blind-except flake8-builtins flake8-class-newline flake8-comprehensions flake8-deprecated flake8-docstrings flake8-import-order flake8-quotes pep8-naming pylint pytest pytest-cov scspell3k>=2.2 [tool:pytest] filterwarnings = error # Suppress deprecation warnings in other packages ignore:lib2to3 package is deprecated::scspell ignore:SelectableGroups dict interface is deprecated::flake8 ignore:Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated::pyreadline junit_suite_name = colcon-python-setup-py [options.entry_points] colcon_core.package_augmentation = python_setup_py = colcon_python_setup_py.package_augmentation.python_setup_py:PythonPackageAugmentation colcon_core.package_identification = python_setup_py = colcon_python_setup_py.package_identification.python_setup_py:PythonPackageIdentification [flake8] import-order-style = google [coverage:run] source = colcon_python_setup_py colcon-python-setup-py-0.2.8/setup.py000066400000000000000000000001721431114503400176070ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from setuptools import setup setup() colcon-python-setup-py-0.2.8/stdeb.cfg000066400000000000000000000002571431114503400176630ustar00rootroot00000000000000[colcon-python-setup-py] No-Python2: Depends3: python3-colcon-core (>= 0.3.10), python3-setuptools Suite: bionic focal jammy stretch buster bullseye X-Python3-Version: >= 3.5 colcon-python-setup-py-0.2.8/test/000077500000000000000000000000001431114503400170545ustar00rootroot00000000000000colcon-python-setup-py-0.2.8/test/spell_check.words000066400000000000000000000002301431114503400224030ustar00rootroot00000000000000apache chdir colcon contextlib distclass hashable iterdir lstrip noqa pathlib plugin pytest pythonpath rtype runpy scspell setuptools stacklevel thomas colcon-python-setup-py-0.2.8/test/test_copyright_license.py000066400000000000000000000024271431114503400242040ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from pathlib import Path import sys def test_copyright_license(): missing = check_files([Path(__file__).parents[1]]) assert not len(missing), \ 'In some files no copyright / license line was found' def check_files(paths): missing = [] for path in paths: if path.is_dir(): for p in sorted(path.iterdir()): if p.name.startswith('.'): continue if p.name.endswith('.py') or p.is_dir(): missing += check_files([p]) if path.is_file(): content = path.read_text() if not content: continue lines = content.splitlines() has_copyright = \ any(line for line in lines if line.startswith('# Copyright')) has_license = \ '# Licensed under the Apache License, Version 2.0' in lines if not has_copyright or not has_license: print( 'Could not find copyright / license in:', path, file=sys.stderr) missing .append(path) else: print('Found copyright / license in:', path) return missing colcon-python-setup-py-0.2.8/test/test_flake8.py000066400000000000000000000030111431114503400216320ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import logging from pathlib import Path import sys from flake8 import LOG from flake8.api.legacy import get_style_guide # avoid debug and info messages from flake8 internals LOG.setLevel(logging.WARN) def test_flake8(): style_guide = get_style_guide( extend_ignore=['D100', 'D104'], show_source=True, ) style_guide_tests = get_style_guide( extend_ignore=['D100', 'D101', 'D102', 'D103', 'D104', 'D105', 'D107'], show_source=True, ) stdout = sys.stdout sys.stdout = sys.stderr # implicitly calls report_errors() report = style_guide.check_files([ str(Path(__file__).parents[1] / 'colcon_python_setup_py'), ]) report_tests = style_guide_tests.check_files([ str(Path(__file__).parents[1] / 'test'), ]) sys.stdout = stdout total_errors = report.total_errors + report_tests.total_errors if total_errors: # pragma: no cover # output summary with per-category counts print() if report.total_errors: report._application.formatter.show_statistics(report._stats) if report_tests.total_errors: report_tests._application.formatter.show_statistics( report_tests._stats) print( 'flake8 reported {total_errors} errors' .format_map(locals()), file=sys.stderr) assert not total_errors, \ 'flake8 reported {total_errors} errors'.format_map(locals()) colcon-python-setup-py-0.2.8/test/test_spell_check.py000066400000000000000000000035641431114503400227510ustar00rootroot00000000000000# Copyright 2016-2019 Dirk Thomas # Licensed under the Apache License, Version 2.0 from pathlib import Path import pytest from scspell import Report from scspell import SCSPELL_BUILTIN_DICT from scspell import spell_check spell_check_words_path = Path(__file__).parent / 'spell_check.words' @pytest.fixture(scope='module') def known_words(): global spell_check_words_path return spell_check_words_path.read_text().splitlines() def test_spell_check(known_words): source_filenames = [Path(__file__).parents[1] / 'setup.py'] + \ list( (Path(__file__).parents[1] / 'colcon_python_setup_py') .glob('**/*.py')) + \ list((Path(__file__).parents[1] / 'test').glob('**/*.py')) for source_filename in sorted(source_filenames): print('Spell checking:', source_filename) # check all files report = Report(known_words) spell_check( [str(p) for p in source_filenames], base_dicts=[SCSPELL_BUILTIN_DICT], report_only=report, additional_extensions=[('', 'Python')]) unknown_word_count = len(report.unknown_words) assert unknown_word_count == 0, \ 'Found {unknown_word_count} unknown words: '.format_map(locals()) + \ ', '.join(sorted(report.unknown_words)) unused_known_words = set(known_words) - report.found_known_words unused_known_word_count = len(unused_known_words) assert unused_known_word_count == 0, \ '{unused_known_word_count} words in the word list are not used: ' \ .format_map(locals()) + ', '.join(sorted(unused_known_words)) def test_spell_check_word_list_order(known_words): assert known_words == sorted(known_words), \ 'The word list should be ordered alphabetically' def test_spell_check_word_list_duplicates(known_words): assert len(known_words) == len(set(known_words)), \ 'The word list should not contain duplicates'