pax_global_header00006660000000000000000000000064145033302020014502gustar00rootroot0000000000000052 comment=bcfd3108b050fa2a18dd40ca52bb1a13b8af00cd colcon-parallel-executor-0.3.0/000077500000000000000000000000001450333020200164055ustar00rootroot00000000000000colcon-parallel-executor-0.3.0/.codecov.yml000066400000000000000000000002221450333020200206240ustar00rootroot00000000000000coverage: status: project: default: informational: true patch: default: only_pulls: true target: 0% colcon-parallel-executor-0.3.0/.github/000077500000000000000000000000001450333020200177455ustar00rootroot00000000000000colcon-parallel-executor-0.3.0/.github/workflows/000077500000000000000000000000001450333020200220025ustar00rootroot00000000000000colcon-parallel-executor-0.3.0/.github/workflows/ci.yaml000066400000000000000000000012571450333020200232660ustar00rootroot00000000000000name: 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 - uses: codecov/codecov-action@v3 colcon-parallel-executor-0.3.0/LICENSE000066400000000000000000000261361450333020200174220ustar00rootroot00000000000000 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-parallel-executor-0.3.0/README.rst000066400000000000000000000002341450333020200200730ustar00rootroot00000000000000colcon-parallel-executor ======================== An extension for `colcon-core `_ to process packages in parallel. colcon-parallel-executor-0.3.0/colcon_parallel_executor/000077500000000000000000000000001450333020200234545ustar00rootroot00000000000000colcon-parallel-executor-0.3.0/colcon_parallel_executor/__init__.py000066400000000000000000000001521450333020200255630ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 __version__ = '0.3.0' colcon-parallel-executor-0.3.0/colcon_parallel_executor/executor/000077500000000000000000000000001450333020200253125ustar00rootroot00000000000000colcon-parallel-executor-0.3.0/colcon_parallel_executor/executor/__init__.py000066400000000000000000000000001450333020200274110ustar00rootroot00000000000000colcon-parallel-executor-0.3.0/colcon_parallel_executor/executor/parallel.py000066400000000000000000000215371450333020200274700ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import asyncio from concurrent.futures import ALL_COMPLETED from concurrent.futures import FIRST_COMPLETED from contextlib import suppress import logging import os import signal import sys import traceback from colcon_core.executor import ExecutorExtensionPoint from colcon_core.executor import OnError from colcon_core.logging import colcon_logger from colcon_core.plugin_system import satisfies_version from colcon_core.subprocess import new_event_loop from colcon_core.subprocess import SIGINT_RESULT logger = colcon_logger.getChild(__name__) def counting_number(value): """Convert a number greater than or equal to zero.""" value = int(value) if value < 0: raise ValueError() return value class ParallelExecutorExtension(ExecutorExtensionPoint): """ Process multiple packages in parallel. The parallelization is honoring the dependency graph between the packages. """ # the priority needs to be higher than the extension providing the # sequential execution in order to become the default PRIORITY = 110 def __init__(self): # noqa: D107 super().__init__() satisfies_version( ExecutorExtensionPoint.EXTENSION_POINT_VERSION, '^1.0') def add_arguments(self, *, parser): # noqa: D102 max_workers_default = os.cpu_count() or 4 with suppress(AttributeError): # consider restricted set of CPUs if applicable max_workers_default = min( max_workers_default, len(os.sched_getaffinity(0))) parser.add_argument( '--parallel-workers', type=counting_number, default=max_workers_default, metavar='NUMBER', help='The maximum number of packages to process in parallel, ' "or '0' for no limit " '(default: {max_workers_default})'.format_map(locals())) def execute(self, args, jobs, *, on_error=OnError.interrupt): # noqa: D102 # avoid debug message from asyncio when colcon uses debug log level asyncio_logger = logging.getLogger('asyncio') asyncio_logger.setLevel(logging.INFO) loop = new_event_loop() asyncio.set_event_loop(loop) coro = self._execute(args, jobs, on_error=on_error) future = asyncio.ensure_future(coro, loop=loop) try: logger.debug('run_until_complete') loop.run_until_complete(future) except KeyboardInterrupt: logger.debug('run_until_complete was interrupted') # override job rc with special SIGINT value for job in self._ongoing_jobs: job.returncode = SIGINT_RESULT # ignore further SIGINTs signal.signal(signal.SIGINT, signal.SIG_IGN) # wait for jobs which have also received a SIGINT if not future.done(): logger.debug('run_until_complete again') loop.run_until_complete(future) assert future.done() # read potential exception to avoid asyncio error _ = future.exception() logger.debug('run_until_complete finished') return signal.SIGINT except Exception as e: # noqa: F841 exc = traceback.format_exc() logger.error( 'Exception in job execution: {e}\n{exc}'.format_map(locals())) return 1 finally: # HACK on Windows closing the event loop seems to hang after Ctrl-C # even though no futures are pending, but appears fixed in py3.8 if sys.platform != 'win32' or sys.version_info >= (3, 8): logger.debug('closing loop') loop.close() logger.debug('loop closed') else: logger.debug('skipping loop closure') result = future.result() logger.debug( "run_until_complete finished with '{result}'".format_map(locals())) return result async def _execute(self, args, jobs, *, on_error): # count the number of dependent jobs for each job # in order to process jobs with more dependent jobs first recursive_dependent_counts = {} for package_name, job in jobs.items(): # ignore "self" dependency recursive_dependent_counts[package_name] = len([ j for name, j in jobs.items() if package_name != name and package_name in j.dependencies]) futures = {} finished_jobs = {} rc = 0 jobs = jobs.copy() while jobs or futures: # determine "ready" jobs ready_jobs = [] for package_name, job in jobs.items(): # a pending job is "ready" when all dependencies have finished not_finished = set(jobs.keys()) | { f.identifier for f in futures.values()} if not (set(job.dependencies) - {package_name}) & not_finished: ready_jobs.append(( package_name, job, recursive_dependent_counts[package_name])) # order the ready jobs, jobs with more dependents first ready_jobs.sort(key=lambda r: -r[2]) # take "ready" jobs take_jobs = [] for package_name, job, _ in ready_jobs: # don't schedule more jobs then workers # to prevent starting further jobs when a job fails if args.parallel_workers: if len(futures) + len(take_jobs) >= args.parallel_workers: break take_jobs.append((package_name, job)) del jobs[package_name] # pass them to the executor for package_name, job in take_jobs: assert asyncio.iscoroutinefunction(job.__call__), \ 'Job is not a coroutine' future = asyncio.ensure_future(job()) futures[future] = job # wait for futures assert futures, 'No futures' self._ongoing_jobs = futures.values() done_futures, _pending = await asyncio.wait( futures.keys(), timeout=30, return_when=FIRST_COMPLETED) if not done_futures: # timeout print( '[Processing: %s]' % ', '.join(sorted( f.identifier for f in futures.values()))) # check results of done futures for done_future in done_futures: job = futures[done_future] del futures[done_future] # get result without raising an exception if done_future.cancelled(): result = signal.SIGINT elif done_future.exception(): result = done_future.exception() if isinstance(result, KeyboardInterrupt): result = signal.SIGINT else: result = done_future.result() if result == SIGINT_RESULT: result = signal.SIGINT finished_jobs[job.identifier] = result # if any job returned a SIGINT overwrite the return code # this should override a potentially earlier set error code # in the case where on_error isn't set to OnError.interrupt # otherwise set the error code if it is the first if result is signal.SIGINT or result and not rc: rc = result if result: if on_error in (OnError.interrupt, OnError.skip_pending): # skip pending jobs jobs.clear() if on_error == OnError.skip_downstream: # skip downstream jobs of failed one for pending_name, pending_job in list(jobs.items()): if job.identifier in pending_job.dependencies: del jobs[pending_name] # if any job failed or was interrupted cancel pending futures if (rc and on_error == OnError.interrupt) or rc is signal.SIGINT: if futures: for future in futures.keys(): if not future.done(): future.cancel() await asyncio.wait( futures.keys(), return_when=ALL_COMPLETED) # collect results from canceled futures for future, job in futures.items(): result = future.result() finished_jobs[job.identifier] = result break # if any job failed if any(finished_jobs.values()): # flush job output self._flush() return rc colcon-parallel-executor-0.3.0/publish-python.yaml000066400000000000000000000005561450333020200222640ustar00rootroot00000000000000artifacts: - 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-parallel-executor-0.3.0/setup.cfg000066400000000000000000000037101450333020200202270ustar00rootroot00000000000000[metadata] name = colcon-parallel-executor version = attr: colcon_parallel_executor.__version__ url = https://colcon.readthedocs.io project_urls = Changelog = https://github.com/colcon/colcon-parallel-executor/milestones?direction=desc&sort=due_date&state=closed GitHub = https://github.com/colcon/colcon-parallel-executor/ 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 process packages in parallel. long_description = file: README.rst keywords = colcon [options] install_requires = colcon-core>=0.3.15 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:pkg_resources is deprecated as an API::flake8_import_order 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-parallel-executor [options.entry_points] colcon_core.executor = parallel = colcon_parallel_executor.executor.parallel:ParallelExecutorExtension [flake8] import-order-style = google [coverage:run] source = colcon_parallel_executor colcon-parallel-executor-0.3.0/setup.py000066400000000000000000000001721450333020200201170ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 from setuptools import setup setup() colcon-parallel-executor-0.3.0/stdeb.cfg000066400000000000000000000002351450333020200201670ustar00rootroot00000000000000[colcon-parallel-executor] No-Python2: Depends3: python3-colcon-core (>= 0.3.15) Suite: bionic focal jammy stretch buster bullseye X-Python3-Version: >= 3.5 colcon-parallel-executor-0.3.0/test/000077500000000000000000000000001450333020200173645ustar00rootroot00000000000000colcon-parallel-executor-0.3.0/test/spell_check.words000066400000000000000000000003051450333020200227160ustar00rootroot00000000000000apache asyncio colcon contextlib coroutine getaffinity getpid getsignal iscoroutinefunction iterdir noqa parallelization pathlib plugin pytest returncode scspell setuptools sigint thomas traceback colcon-parallel-executor-0.3.0/test/test_copyright_license.py000066400000000000000000000024271450333020200245140ustar00rootroot00000000000000# 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-parallel-executor-0.3.0/test/test_executor_parallel.py000066400000000000000000000126331450333020200245140ustar00rootroot00000000000000# Copyright 2016-2018 Dirk Thomas # Licensed under the Apache License, Version 2.0 import asyncio from collections import OrderedDict import os import signal import sys from threading import Thread import time from types import SimpleNamespace from colcon_core.executor import Job from colcon_core.executor import OnError from colcon_core.subprocess import SIGINT_RESULT from colcon_parallel_executor.executor.parallel \ import ParallelExecutorExtension import pytest ran_jobs = [] class Job1(Job): def __init__(self): super().__init__( identifier='job1', dependencies=set(), task=None, task_context=None) async def __call__(self, *args, **kwargs): global ran_jobs ran_jobs.append(self.identifier) class Job2(Job): def __init__(self): super().__init__( identifier='job2', dependencies=set(), task=None, task_context=None) async def __call__(self, *args, **kwargs): return 2 class Job3(Job): def __init__(self): super().__init__( identifier='job3', dependencies=set(), task=None, task_context=None) async def __call__(self, *args, **kwargs): raise RuntimeError('custom exception') class Job4(Job): def __init__(self): super().__init__( identifier='job4', dependencies=set(), task=None, task_context=None) async def __call__(self, *args, **kwargs): global ran_jobs try: await asyncio.sleep(0.05) except asyncio.CancelledError: return SIGINT_RESULT ran_jobs.append(self.identifier) class Job5(Job): def __init__(self): super().__init__( identifier='job5', dependencies=set(), task=None, task_context=None) async def __call__(self, *args, **kwargs): return 5 class Job6(Job): def __init__(self): super().__init__( identifier='job6', dependencies=('job2', ), task=None, task_context=None) async def __call__(self, *args, **kwargs): global ran_jobs ran_jobs.append(self.identifier) class Job7(Job): def __init__(self): super().__init__( identifier='job7', dependencies=('job1', ), task=None, task_context=None) async def __call__(self, *args, **kwargs): global ran_jobs ran_jobs.append(self.identifier) def test_parallel(): global ran_jobs extension = ParallelExecutorExtension() args = SimpleNamespace(parallel_workers=2) jobs = OrderedDict() jobs['one'] = Job1() # success rc = extension.execute(args, jobs) assert rc == 0 assert ran_jobs == ['job1'] ran_jobs.clear() # return error code jobs['two'] = Job2() jobs['four'] = Job4() rc = extension.execute(args, jobs) assert rc == 2 assert ran_jobs == ['job1'] ran_jobs.clear() rc = extension.execute(args, jobs, on_error=OnError.skip_pending) assert rc == 2 assert ran_jobs == ['job1'] ran_jobs.clear() # return error code, but with more workers args.parallel_workers = 3 rc = extension.execute(args, jobs) assert rc == 2 assert ran_jobs == ['job1'] ran_jobs.clear() rc = extension.execute(args, jobs, on_error=OnError.skip_pending) assert rc == 2 assert ran_jobs == ['job1', 'job4'] ran_jobs.clear() # continue after error, keeping first error code jobs['five'] = Job5() rc = extension.execute(args, jobs, on_error=OnError.continue_) assert rc == 2 assert ran_jobs == ['job1', 'job4'] ran_jobs.clear() # continue but skip downstream jobs['six'] = Job6() jobs['seven'] = Job7() rc = extension.execute(args, jobs, on_error=OnError.skip_downstream) assert rc == 2 assert ran_jobs == ['job1', 'job7', 'job4'] ran_jobs.clear() # exception jobs['two'] = Job3() rc = extension.execute(args, jobs) assert isinstance(rc, RuntimeError) assert ran_jobs == ['job1'] ran_jobs.clear() class Job8(Job): def __init__(self): super().__init__( identifier='job8', dependencies=set(), task=None, task_context=None) async def __call__(self, *args, **kwargs): global ran_jobs await asyncio.sleep(3) ran_jobs.append(self.identifier) @pytest.fixture def restore_sigint_handler(): handler = signal.getsignal(signal.SIGINT) yield signal.signal(signal.SIGINT, handler) def test_parallel_keyboard_interrupt(restore_sigint_handler): global ran_jobs if sys.platform == 'win32': pytest.skip( 'Skipping keyboard interrupt test since the signal will cause ' 'pytest to return failure even if no tests fail.') extension = ParallelExecutorExtension() args = SimpleNamespace(parallel_workers=3) jobs = OrderedDict() jobs['one'] = Job1() jobs['aborted'] = Job8() jobs['four'] = Job4() def delayed_sigint(): time.sleep(0.1) # Note: a real Ctrl-C would signal the whole process group os.kill( os.getpid(), signal.SIGINT if sys.platform != 'win32' else signal.CTRL_C_EVENT) if sys.platform == 'win32': os.kill(os.getpid(), signal.CTRL_C_EVENT) thread = Thread(target=delayed_sigint) thread.start() try: rc = extension.execute(args, jobs) finally: thread.join() assert rc == signal.SIGINT ran_jobs.clear() colcon-parallel-executor-0.3.0/test/test_flake8.py000066400000000000000000000030131450333020200221440ustar00rootroot00000000000000# 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_parallel_executor'), ]) 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-parallel-executor-0.3.0/test/test_spell_check.py000066400000000000000000000035661450333020200232630ustar00rootroot00000000000000# 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_parallel_executor') .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'