diff --git a/.coveragerc b/.coveragerc index 5dfabb63..cfc966e1 100644 --- a/.coveragerc +++ b/.coveragerc @@ -21,6 +21,7 @@ exclude_lines = raise ImportError raise baton baton = ImportError + raise ModuleNotFoundError baton.module except subprocess.CalledProcessError except ..Error @@ -56,5 +57,6 @@ partial_branches = if 'os' not in sys.modules: if 'os.path' not in sys.modules: if 'argparse' not in sys.modules: + RuntimeError("SHUTDOWN") diff --git a/.github/labeler.yml b/.github/labeler.yml index 1c39b6cc..0ce0bc7c 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -88,5 +88,7 @@ Github: - README.md invalid: + - changed-files: + - any-glob-to-any-file: - .stickler.yml - .hound.yml diff --git a/multicast/__init__.py b/multicast/__init__.py index 4707088d..e7618955 100644 --- a/multicast/__init__.py +++ b/multicast/__init__.py @@ -16,7 +16,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Contains the Python Multicast library.""" +import sys +import argparse +import unicodedata +import socket +import struct +import abc + # skipcq __all__ = [ @@ -29,6 +35,7 @@ """recv.McastRECV""", """send.McastSAY""", """hear.McastHEAR""", ] + __package__ = """multicast""" # skipcq: PYL-W0622 """The package of this program. @@ -317,58 +324,37 @@ """ -try: - import sys - if sys.__name__ is None: - raise ImportError("FAIL: we could not import os. We're like in the matrix! ABORT.") -except Exception as err: - raise ImportError(err) +if sys.__name__ is None: + raise ModuleNotFoundError( + "FAIL: we could not import sys. We're like in the matrix! ABORT." + ) from None -try: - import argparse - if argparse.__name__ is None: - raise ImportError("FAIL: we could not import argparse. ABORT.") -except Exception as err: - raise ImportError(err) +if argparse.__name__ is None: + raise ModuleNotFoundError("FAIL: we could not import argparse. ABORT.") from None -try: - import unicodedata - if unicodedata.__name__ is None: - raise ImportError("FAIL: we could not import unicodedata. ABORT.") -except Exception as err: - raise ImportError(err) +if unicodedata.__name__ is None: + raise ModuleNotFoundError("FAIL: we could not import unicodedata. ABORT.") from None -try: - import socket - if socket.__name__ is None: - raise ImportError("FAIL: we could not import socket. ABORT.") - else: # pragma: no branch - socket.setdefaulttimeout(int(_MCAST_DEFAULT_TTL)) -except Exception as err: - raise ImportError(err) +if socket.__name__ is None: + raise ModuleNotFoundError("FAIL: we could not import socket. ABORT.") from None +else: # pragma: no branch + socket.setdefaulttimeout(int(_MCAST_DEFAULT_TTL)) -try: - import struct - if struct.__name__ is None: - raise ImportError("FAIL: we could not import struct. ABORT.") -except Exception as err: - raise ImportError(err) +if struct.__name__ is None: + raise ModuleNotFoundError("FAIL: we could not import struct. ABORT.") from None -try: - import abc - if abc.__name__ is None: - raise ImportError("FAIL: we could not import Abstract base class. ABORT.") -except Exception as err: - raise ImportError(err) +if abc.__name__ is None: + raise ModuleNotFoundError("FAIL: we could not import Abstract base class. ABORT.") from None class mtool(abc.ABC): - """Class for Multicast tools. + """ + Class for Multicast tools. Utility class for CLI tools of the Multicast package. setupArgs() and doStep() are abstract and need to be implemented by subclasses. @@ -395,7 +381,8 @@ class mtool(abc.ABC): @classmethod def buildArgs(cls, calling_parser_group): - """Will build the argparse parser. + """ + Will build the argparse parser. Utility Function to build the argparse parser; see argparse.ArgumentParser for more. returns argparse.ArgumentParser - the ArgumentParser to use. @@ -466,7 +453,8 @@ def buildArgs(cls, calling_parser_group): @classmethod def parseArgs(cls, arguments=None): - """Will attempt to parse the given CLI arguments. + """ + Will attempt to parse the given CLI arguments. See argparse.ArgumentParser for more. param str - arguments - the array of arguments to parse. Usually sys.argv[1:] @@ -520,7 +508,8 @@ def parseArgs(cls, arguments=None): @classmethod def checkToolArgs(cls, args): - """Will handle the None case for arguments. + """ + Will handle the None case for arguments. Used as a helper function. @@ -566,7 +555,8 @@ def checkToolArgs(cls, args): return [None] if args is None else args def __call__(self, *args, **kwargs): - """Call self as a function. + """ + Call self as a function. Default implementation simply calls the abstract function doStep and passes the given positional arguments, thus key-word arguments @@ -589,14 +579,10 @@ def doStep(self, *args): # pragma: no cover pass # skipcq - abstract method -try: - if 'multicast.skt' not in sys.modules: - from . import skt as skt # pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414 - else: # pragma: no branch - skt = sys.modules["""multicast.skt"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast.skt as skt # pylint: disable=cyclic-import - skipcq: PYL-R0401 +if 'multicast.skt' not in sys.modules: + from . import skt as skt # pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414 +else: # pragma: no branch + skt = sys.modules["""multicast.skt"""] genSocket = skt.genSocket @@ -605,34 +591,22 @@ def doStep(self, *args): # pragma: no cover endSocket = skt.endSocket -try: - if 'multicast.recv' not in sys.modules: - from . import recv as recv # pylint: disable=cyclic-import - skipcq: PYL-R0401 - else: # pragma: no branch - recv = sys.modules["""multicast.recv"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast.recv as recv # pylint: disable=cyclic-import - skipcq: PYL-R0401 +if 'multicast.recv' not in sys.modules: + from . import recv as recv # pylint: disable=cyclic-import - skipcq: PYL-R0401 +else: # pragma: no branch + recv = sys.modules["""multicast.recv"""] -try: - if 'multicast.send' not in sys.modules: - from . import send as send # pylint: disable=cyclic-import - skipcq: PYL-R0401 - else: # pragma: no branch - send = sys.modules["""multicast.send"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast.send as send # pylint: disable=cyclic-import - skipcq: PYL-R0401 +if 'multicast.send' not in sys.modules: + from . import send as send # pylint: disable=cyclic-import - skipcq: PYL-R0401 +else: # pragma: no branch + send = sys.modules["""multicast.send"""] -try: - if 'multicast.hear' not in sys.modules: - from . import hear as hear # pylint: disable=cyclic-import - skipcq: PYL-R0401 - else: # pragma: no branch - hear = sys.modules["""multicast.hear"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast.hear as hear # pylint: disable=cyclic-import - skipcq: PYL-R0401 +if 'multicast.hear' not in sys.modules: + from . import hear as hear # pylint: disable=cyclic-import - skipcq: PYL-R0401 +else: # pragma: no branch + hear = sys.modules["""multicast.hear"""] try: diff --git a/multicast/__main__.py b/multicast/__main__.py index 6a32e0d1..04b9c6fc 100644 --- a/multicast/__main__.py +++ b/multicast/__main__.py @@ -77,79 +77,51 @@ try: from . import sys as _sys -except Exception: +except Exception as impErr: # Throw more relevant Error - raise ImportError(str("[CWE-440] Error Importing Python")) + raise ImportError(str("[CWE-440] Error Importing Python")) from impErr -try: - if 'multicast.__version__' not in _sys.modules: - from . import __version__ as __version__ # skipcq: PYL-C0414 - else: # pragma: no branch - __version__ = _sys.modules["""multicast.__version__"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast.__version__ as __version__ # noqa. skipcq - used by --version argument. +if 'multicast.__version__' not in _sys.modules: + from . import __version__ as __version__ # skipcq: PYL-C0414 +else: # pragma: no branch + __version__ = _sys.modules["""multicast.__version__"""] -try: - if 'multicast._MCAST_DEFAULT_PORT' not in _sys.modules: - from . import _MCAST_DEFAULT_PORT as _MCAST_DEFAULT_PORT # skipcq: PYL-C0414 - else: # pragma: no branch - _MCAST_DEFAULT_PORT = _sys.modules["""multicast._MCAST_DEFAULT_PORT"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast._MCAST_DEFAULT_PORT as _MCAST_DEFAULT_PORT # skipcq - used by port argument. +if 'multicast._MCAST_DEFAULT_PORT' not in _sys.modules: + from . import _MCAST_DEFAULT_PORT as _MCAST_DEFAULT_PORT # skipcq: PYL-C0414 +else: # pragma: no branch + _MCAST_DEFAULT_PORT = _sys.modules["""multicast._MCAST_DEFAULT_PORT"""] -try: - if 'multicast._MCAST_DEFAULT_GROUP' not in _sys.modules: - from . import _MCAST_DEFAULT_GROUP as _MCAST_DEFAULT_GROUP # skipcq: PYL-C0414 - else: # pragma: no branch - _MCAST_DEFAULT_GROUP = _sys.modules["""multicast._MCAST_DEFAULT_GROUP"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast._MCAST_DEFAULT_GROUP as _MCAST_DEFAULT_GROUP # skipcq - used by group arg. +if 'multicast._MCAST_DEFAULT_GROUP' not in _sys.modules: + from . import _MCAST_DEFAULT_GROUP as _MCAST_DEFAULT_GROUP # skipcq: PYL-C0414 +else: # pragma: no branch + _MCAST_DEFAULT_GROUP = _sys.modules["""multicast._MCAST_DEFAULT_GROUP"""] -try: - if 'multicast.mtool' not in _sys.modules: - from . import mtool as mtool # skipcq: PYL-C0414 - else: # pragma: no branch - mtool = _sys.modules["""multicast.mtool"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast.mtool as mtool # noqa - used by all arguments' CMD (sub-command). +if 'multicast.mtool' not in _sys.modules: + from . import mtool as mtool # skipcq: PYL-C0414 +else: # pragma: no branch + mtool = _sys.modules["""multicast.mtool"""] -try: - if 'multicast.recv' not in _sys.modules: - from . import recv as recv # pylint: disable=useless-import-alias - skipcq: PYL-C0414 - else: # pragma: no branch - recv = _sys.modules["""multicast.recv"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast.recv as recv # pylint: disable=useless-import-alias - skipcq: PYL-C0414 +if 'multicast.recv' not in _sys.modules: + from . import recv as recv # pylint: disable=useless-import-alias - skipcq: PYL-C0414 +else: # pragma: no branch + recv = _sys.modules["""multicast.recv"""] -try: - if 'multicast.send' not in _sys.modules: - from . import send as send # pylint: disable=useless-import-alias - skipcq: PYL-C0414 - else: # pragma: no branch - send = _sys.modules["""multicast.send"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast.send as send # pylint: disable=useless-import-alias - skipcq: PYL-C0414 +if 'multicast.send' not in _sys.modules: + from . import send as send # pylint: disable=useless-import-alias - skipcq: PYL-C0414 +else: # pragma: no branch + send = _sys.modules["""multicast.send"""] -try: - if 'multicast.hear' not in _sys.modules: - from . import hear as hear # pylint: disable=useless-import-alias - skipcq: PYL-C0414 - else: # pragma: no branch - hear = _sys.modules["""multicast.hear"""] -except Exception as importErr: - del importErr # skipcq - cleanup any error leaks early - import multicast.hear as hear # pylint: disable=useless-import-alias - skipcq: PYL-C0414 +if 'multicast.hear' not in _sys.modules: + from . import hear as hear # pylint: disable=useless-import-alias - skipcq: PYL-C0414 +else: # pragma: no branch + hear = _sys.modules["""multicast.hear"""] class McastNope(mtool): @@ -462,8 +434,8 @@ def doStep(self, *args, **kwargs): This method selects either the `McastHEAR` or `McastRECV` class based on the daemon dispatch flag and executes the corresponding step. - The RECV (via McastRECV) is the primitive sub-command to recieve a single multicas hunk. - The HEAR (via McastHEAR) is equivilant to running RECV in a loop to continually recive + The RECV (via McastRECV) is the primitive sub-command to receive a single multicas hunk. + The HEAR (via McastHEAR) is equivalent to running RECV in a loop to continually receive multiple hunks. Most use-case will probably want to use HEAR instead of RECV. Args: diff --git a/multicast/hear.py b/multicast/hear.py index 14187f06..5a098a5d 100644 --- a/multicast/hear.py +++ b/multicast/hear.py @@ -183,8 +183,8 @@ try: + import threading import socketserver - import threading as _threading from multicast import argparse as _argparse from multicast import unicodedata as _unicodedata from multicast import socket as _socket @@ -195,17 +195,18 @@ for unit in depends: try: if unit.__name__ is None: # pragma: no branch - raise ImportError( + raise ModuleNotFoundError( str("[CWE-440] module failed to import {}.").format(str(unit)) - ) + ) from None except Exception: # pragma: no branch - raise ImportError(str("[CWE-758] Module failed completely.")) + raise ModuleNotFoundError(str("[CWE-758] Module failed completely.")) from None except Exception as err: - raise ImportError(err) + raise ImportError(err) from err class McastServer(socketserver.UDPServer): - """Generic Subclasses socketserver.UDPServer for handling daemon function. + """ + Generic Subclasses socketserver.UDPServer for handling daemon function. Basically simplifies testing by allowing a trivial echo back (case-insensitive) of string data, after printing the sender's ip out. @@ -259,13 +260,14 @@ def handle_error(self, request, client_address): def kill_func(a_server): if a_server is not None: a_server.shutdown() - end_thread = _threading.Thread(name="Kill_Thread", target=kill_func, args=[self]) + end_thread = threading.Thread(name="Kill_Thread", target=kill_func, args=[self]) end_thread.start() super(McastServer, self).handle_error(request, client_address) class MyUDPHandler(socketserver.BaseRequestHandler): - """Subclasses socketserver.BaseRequestHandler for handling echo function. + """ + Subclasses socketserver.BaseRequestHandler for handling echo function. Basically simplifies testing by allowing a trivial echo back (case-insensitive) of string data, after printing the sender's ip out. @@ -300,7 +302,8 @@ def handle(self): class HearUDPHandler(socketserver.BaseRequestHandler): - """Subclasses socketserver.BaseRequestHandler for handling HEAR function. + """ + Subclasses socketserver.BaseRequestHandler for handling HEAR function. Basically simplifies testing by allowing a simple HEAR back (case-insensitive) of string data, after printing the sender's ip out. @@ -351,11 +354,12 @@ def handle(self): ) ) if """STOP""" in str(data): - raise RuntimeError("SHUTDOWN") + raise RuntimeError("SHUTDOWN") from None class McastHEAR(multicast.mtool): - """Subclasses multicast.mtool to provide the HEAR tooling. + """ + Subclasses multicast.mtool to provide the HEAR tooling. Testing: diff --git a/multicast/recv.py b/multicast/recv.py index 72c4ffbf..f938c08e 100644 --- a/multicast/recv.py +++ b/multicast/recv.py @@ -30,7 +30,7 @@ # .......................................... # NO ASSOCIATION -"""multicast RECV Features. +"""Multicast RECV Features. Caution: See details regarding dynamic imports [documented](../__init__.py) in this module. @@ -198,21 +198,22 @@ ] for unit in depends: if unit.__name__ is None: # pragma: no branch - baton = ImportError( + baton = ModuleNotFoundError( str("[CWE-440] module failed to import {}.").format(str(unit)) ) # pragma: no cover baton.module = unit # pragma: no cover - raise baton # pragma: no cover + raise baton from None # pragma: no cover except Exception as err: baton = ImportError(err, str("[CWE-758] Module failed completely.")) baton.module = __module__ baton.path = __file__ baton.__cause__ = err - raise baton + raise baton from err def joinstep(groups, port, iface=None, bind_group=None, isock=None): - """Will join the given multicast group(s). + """ + Will join the given multicast group(s). The JOIN function. Will start to listen on the given port of an interface for multicast messages to the given group(s). @@ -272,12 +273,13 @@ def joinstep(groups, port, iface=None, bind_group=None, isock=None): ) sock.setsockopt(_socket.IPPROTO_IP, _socket.IP_ADD_MEMBERSHIP, mreq) except Exception as err: # pragma: no branch - raise NotImplementedError("""[CWE-440] Not Implemented.""", err) # pragma: no cover + raise NotImplementedError("""[CWE-440] Not Implemented.""", err) from err # pragma: no cover return sock def tryrecv(msgbuffer, chunk, sock): - """Will try to listen on the given socket directly into the given chunk for decoding. + """ + Will try to listen on the given socket directly into the given chunk for decoding. If the read into the chunk results in content, the chunk will be decoded into the given message buffer. Either way the message buffer will be returned. @@ -339,7 +341,8 @@ def recvstep(msgbuffer, chunk, sock): class McastRECV(multicast.mtool): - """Subclasses the multicast.mtool to provide the RECV functions. + """ + Subclasses the multicast.mtool to provide the RECV functions. Testing: @@ -394,7 +397,8 @@ class McastRECV(multicast.mtool): @classmethod def setupArgs(cls, parser): - """Will attempt add send args. + """ + Will attempt add send args. Testing: @@ -474,7 +478,8 @@ def setupArgs(cls, parser): @staticmethod def _hearstep(groups, port, iface=None, bind_group=None): - """Will listen on the given port of an interface for multicast messages to the given group(s). + """ + Will listen on the given port of an interface for multicast messages to the given group(s). The work-horse function. diff --git a/multicast/send.py b/multicast/send.py index 969b239e..55b8c8d9 100644 --- a/multicast/send.py +++ b/multicast/send.py @@ -164,15 +164,16 @@ if unit.__name__ is None: # pragma: no branch raise ImportError( str("[CWE-440] module failed to import {}.").format(str(unit)) - ) - except Exception: # pragma: no branch - raise ImportError(str("[CWE-758] Module failed completely.")) + ) from None + except Exception as _cause: # pragma: no branch + raise ImportError(str("[CWE-758] Module failed completely.")) from _cause except Exception as err: - raise ImportError(err) + raise ImportError(err) from err class McastSAY(multicast.mtool): - """Multicast Broacaster tool. + """ + Multicast Broacaster tool. Testing: @@ -217,7 +218,8 @@ class McastSAY(multicast.mtool): @classmethod def setupArgs(cls, parser): - """Will attempt add send args. + """ + Will attempt add send args. Testing: @@ -297,7 +299,8 @@ def setupArgs(cls, parser): @staticmethod def _sayStep(group, port, data): - """Will send the given data over the given port to the given group. + """ + Will send the given data over the given port to the given group. The actual magic is handled here. """ diff --git a/multicast/skt.py b/multicast/skt.py index 8c92a9da..7151d773 100644 --- a/multicast/skt.py +++ b/multicast/skt.py @@ -161,11 +161,11 @@ baton.module = __module__ baton.path = __file__ baton.__cause__ = err - raise baton + raise baton from err def genSocket(): - """Will generate an unbound socket.socket object ready to receive network traffic. + """Generates an unbound socket.socket object ready to receive network traffic. Implementation allows reuse of socket (to allow another instance of python running this script binding to the same ip/port). @@ -212,7 +212,7 @@ def genSocket(): def endSocket(sock=None): - """Will generates an unbound socket.socket object ready to receive network traffic. + """Closes a given socket.socket object. Minimal Acceptance Testing: diff --git a/setup.py b/setup.py index 6e6b94ac..175b4fdf 100755 --- a/setup.py +++ b/setup.py @@ -44,8 +44,8 @@ from setuptools.config import read_configuration except Exception: from setuptools.config.setupcfg import read_configuration -except Exception: - raise NotImplementedError("""[CWE-440] Not Implemented.""") +except Exception as err: + raise NotImplementedError("""[CWE-440] Not Implemented.""") from err def readFile(filename): @@ -73,10 +73,8 @@ def readFile(filename): try: expected_files = ["""E.md""", """requirements.txt"""] if not any(aexpected_file in filename for aexpected_file in expected_files): - raise ValueError(str( - """[CWE-706] Access to the file {} was not expected.""" - ).format(filename)) - with open(str("""./{}""").format(str(filename))) as f: + raise ValueError(f"[CWE-706] Access to the file {filename} was not expected.") from None + with open(f"./{filename}") as f: theResult = f.read() except Exception as err: theResult = str( @@ -116,7 +114,7 @@ def parse_requirements_for_install_requires(requirements_text): version = match.group(3) if operator == '>=' and version: # Keep only the minimum required version - install_requires.append(str("{pkg}>={ver}").format(pkg=package, ver=version)) + install_requires.append(f"{package}>={version}") elif version: # Include the package without version or with simplified specifier install_requires.append(package) diff --git a/tests/__init__.py b/tests/__init__.py index ba538bbc..2aa04d83 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -44,9 +44,9 @@ try: import sys if sys.__name__ is None: # pragma: no branch - raise ImportError("[CWE-440] OMG! we could not import sys. ABORT. ABORT.") + raise ModuleNotFoundError("[CWE-440] OMG! we could not import sys. ABORT. ABORT.") from None except Exception as err: # pragma: no branch - raise ImportError(err) + raise ImportError(err) from err try: @@ -54,8 +54,8 @@ import os else: # pragma: no branch os = sys.modules["""os"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] OS Failed to import.") +except Exception as err: # pragma: no branch + raise ModuleNotFoundError("[CWE-440] OS Failed to import.") from err try: @@ -63,8 +63,8 @@ import unittest else: # pragma: no branch unittest = sys.modules["""unittest"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] unittest Failed to import.") +except Exception as err: # pragma: no branch + raise ModuleNotFoundError("[CWE-440] unittest Failed to import.") from err try: @@ -72,8 +72,8 @@ import functools else: # pragma: no branch functools = sys.modules["""functools"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] functools Failed to import.") +except Exception as err: # pragma: no branch + raise ModuleNotFoundError("[CWE-440] functools Failed to import.") from err try: @@ -81,8 +81,8 @@ import multicast # pylint: disable=cyclic-import - skipcq: PYL-R0401 else: # pragma: no branch multicast = sys.modules["""multicast"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] multicast Failed to import.") +except Exception as err: # pragma: no branch + raise ImportError("[CWE-440] multicast Failed to import.") from err try: @@ -109,16 +109,9 @@ if unit_test.__name__ is None: # pragma: no branch raise ImportError( str("Test module failed to import even the {} tests.").format(str(unit_test)) - ) + ) from None except Exception as impErr: # pragma: no branch - print(str('')) - print(str(type(impErr))) - print(str(impErr)) - print(str((impErr.args))) - print(str('')) - impErr = None - del impErr # skipcq - cleanup any error leaks early - raise ImportError(str("[CWE-758] Test module failed completely.")) + raise ImportError(str("[CWE-758] Test module failed completely.")) from impErr except Exception as badErr: # pragma: no branch print(str('')) print(str(type(badErr))) @@ -135,8 +128,8 @@ from tests import context else: # pragma: no branch context = sys.modules["""tests.context"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] context Failed to import.") +except Exception as _cause: # pragma: no branch + raise ImportError("[CWE-440] context Failed to import.") from _cause test_cases = ( @@ -168,8 +161,8 @@ def load_tests(loader, tests, pattern): import doctest else: # pragma: no branch doctest = sys.modules["""doctest"""] - except Exception: # pragma: no branch - raise ImportError("[CWE-440] doctest Failed to import.") + except Exception as _cause: # pragma: no branch + raise ImportError("[CWE-440] doctest Failed to import.") from _cause finder = doctest.DocTestFinder(verbose=True, recurse=True, exclude_empty=True) suite = unittest.TestSuite() for test_class in test_cases: diff --git a/tests/context.py b/tests/context.py index 70b91619..13447f9a 100644 --- a/tests/context.py +++ b/tests/context.py @@ -55,9 +55,9 @@ try: import sys if sys.__name__ is None: # pragma: no branch - raise ImportError("[CWE-758] OMG! we could not import sys! ABORT. ABORT.") + raise ModuleNotFoundError("[CWE-758] OMG! we could not import sys! ABORT. ABORT.") from None except Exception as err: # pragma: no branch - raise ImportError(err) + raise ImportError(err) from err try: @@ -65,8 +65,8 @@ import os else: # pragma: no branch os = sys.modules["""os"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] OS Failed to import.") +except Exception as err: # pragma: no branch + raise ModuleNotFoundError("[CWE-440] OS Failed to import.") from err try: @@ -74,8 +74,8 @@ import unittest else: # pragma: no branch unittest = sys.modules["""unittest"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] unittest Failed to import.") +except Exception as err: # pragma: no branch + raise ModuleNotFoundError("[CWE-440] unittest Failed to import.") from err try: @@ -83,8 +83,8 @@ from multiprocessing import Process as Process # skipcq: PYL-C0414 else: # pragma: no branch Process = sys.modules["""Process"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] Process Failed to import.") +except Exception as err: # pragma: no branch + raise ModuleNotFoundError("[CWE-440] Process Failed to import.") from err try: @@ -92,8 +92,8 @@ import subprocess else: # pragma: no branch subprocess = sys.modules["""subprocess"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] subprocess Failed to import.") +except Exception as err: # pragma: no branch + raise ModuleNotFoundError("[CWE-440] subprocess Failed to import.") from err try: @@ -101,8 +101,8 @@ import multicast # pylint: disable=cyclic-import - skipcq: PYL-R0401 else: # pragma: no branch multicast = sys.modules["""multicast"""] # pylint: disable=cyclic-import -except Exception: # pragma: no branch - raise ImportError("[CWE-440] Python Multicast Repo Failed to import.") +except Exception as err: # pragma: no branch + raise ImportError("[CWE-440] Python Multicast Repo Failed to import.") from err try: @@ -110,8 +110,8 @@ import tests.profiling as profiling else: # pragma: no branch profiling = sys.modules["""tests.profiling"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] profiling Failed to import.") +except Exception as err: # pragma: no branch + raise ModuleNotFoundError("[CWE-440] profiling Failed to import.") from err __BLANK = str("""""") @@ -172,7 +172,7 @@ def getCoverageCommand(): else: # pragma: no branch thecov = "exit 1 ; #" except Exception: # pragma: no branch - thecov = "exit 1 ; #" + thecov = "exit 1 ; #" # handled error by suppressing it and indicating caller should abort. return str(thecov) @@ -216,7 +216,7 @@ def __check_cov_before_py(): if coverage.__name__ is not None: thepython = str("{} -m coverage run -p").format(str(sys.executable)) except Exception: - thepython = str(sys.executable) + thepython = str(sys.executable) # handled error by falling back on faile-safe value. return str(thepython) @@ -248,7 +248,7 @@ def getPythonCommand(): try: thepython = str(sys.executable) except Exception: - thepython = "exit 1 ; #" + thepython = "exit 1 ; #" # handled error by suppressing it and indicating exit. return str(thepython) @@ -306,9 +306,9 @@ def checkCovCommand(*args): # skipcq: PYL-W0102 - [] != [None] """ if sys.__name__ is None: # pragma: no branch - raise ImportError("[CWE-758] Failed to import system. WTF?!!") + raise ImportError("[CWE-758] Failed to import system. WTF?!!") from None if not args or args[0] is None: - raise RuntimeError("[CWE-1286] args must be an array of positional arguments") + raise RuntimeError("[CWE-1286] args must be an array of positional arguments") from None else: args = [*args] # convert to an array if str("coverage") in args[0]: @@ -573,7 +573,7 @@ def checkPythonFuzzing(args, stderr=None): # skipcq: PYL-W0102 - [] != [None] theOutput = subprocess.check_output(args, stderr=stderr) except BaseException as err: # pragma: no branch theOutput = None - raise RuntimeError(err) # do not suppress all errors + raise RuntimeError(err) from err # do not suppress all errors theOutput = checkStrOrByte(theOutput) return theOutput diff --git a/tests/profiling.py b/tests/profiling.py index df37c8eb..273ac984 100644 --- a/tests/profiling.py +++ b/tests/profiling.py @@ -36,13 +36,13 @@ try: import sys if sys.__name__ is None: # pragma: no branch - raise ImportError("[CWE-758] OMG! we could not import sys! ABORT. ABORT.") + raise ImportError("[CWE-758] OMG! we could not import sys! ABORT. ABORT.") from None except Exception as badErr: # pragma: no branch baton = ImportError(badErr, str("[CWE-758] Test module failed completely.")) baton.module = __module__ baton.path = __file__ baton.__cause__ = badErr - raise baton + raise baton from badErr try: @@ -55,7 +55,7 @@ baton.module = __module__ baton.path = __file__ baton.__cause__ = badErr - raise baton + raise baton from badErr try: @@ -68,7 +68,7 @@ baton.module = __module__ baton.path = __file__ baton.__cause__ = badErr - raise baton + raise baton from badErr try: @@ -80,7 +80,7 @@ baton.module = __module__ baton.path = __file__ baton.__cause__ = badErr - raise baton + raise baton from badErr try: @@ -93,21 +93,21 @@ baton.module = __module__ baton.path = __file__ baton.__cause__ = badErr - raise baton + raise baton from badErr try: try: sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), str('..')))) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), str('.')))) - except Exception as ImportErr: # pragma: no branch - raise ImportError(ImportErr, str("[CWE-758] Profile module failed completely.")) + except Exception as impErr: # pragma: no branch + raise ImportError(impErr, str("[CWE-758] Profile module failed completely.")) from impErr except Exception as badErr: # pragma: no branch baton = ImportError(badErr, str("[CWE-758] Test module failed completely.")) baton.module = __module__ baton.path = __file__ baton.__cause__ = badErr - raise baton + raise baton from badErr class timewith(): @@ -261,7 +261,7 @@ def nothing(*args, **kwargs): def main(argv=None): # pragma: no cover """The Main Event makes no sense to profiling.""" - raise NotImplementedError("CRITICAL - test profiling main() not implemented. yet?") + raise NotImplementedError("CRITICAL - test profiling main() not implemented. yet?") from None if __name__ in '__main__': # pragma: no cover diff --git a/tests/test_basic.py b/tests/test_basic.py index 7d5e591d..5a470410 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -27,12 +27,12 @@ del ImportErr # skipcq - cleanup any error leaks early from . import context if context.__name__ is None: - raise ImportError("[CWE-758] Failed to import context") + raise ImportError("[CWE-758] Failed to import context") from None else: from context import unittest from context import sys as _sys -except Exception: # pragma: no branch - raise ImportError("[CWE-758] Failed to import test context") +except Exception as _cause: # pragma: no branch + raise ImportError("[CWE-758] Failed to import test context") from _cause class BasicTestSuite(context.BasicUsageTestSuite): @@ -105,7 +105,7 @@ def test_Error_WHEN_the_help_command_is_called(self): multicast.main(["--help"]) theResult = True except Exception: - theResult = False + theResult = False # suppress non-testing errors self.assertTrue(theResult) def test_IsNone_WHEN_given_corner_case_input(self): diff --git a/tests/test_build.py b/tests/test_build.py index f9ef41c0..37cac256 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -27,15 +27,15 @@ del ImportErr # skipcq - cleanup any error leaks early from . import context if context.__name__ is None: - raise ImportError("[CWE-758] Failed to import context") + raise ImportError("[CWE-758] Failed to import context") from None else: from context import unittest from context import subprocess from context import os as _os from context import sys as _sys from context import BasicUsageTestSuite -except Exception: # pragma: no branch - raise ImportError("[CWE-758] Failed to import test context") +except Exception as _cause: # pragma: no branch + raise ImportError("[CWE-758] Failed to import test context") from _cause class TestPEP517Build(BasicUsageTestSuite): diff --git a/tests/test_deps.py b/tests/test_deps.py index 8a5a7481..927f3cde 100644 --- a/tests/test_deps.py +++ b/tests/test_deps.py @@ -27,29 +27,29 @@ del ImportErr # skipcq - cleanup any error leaks early from . import context if context.__name__ is None: - raise ImportError("[CWE-758] Failed to import context") + raise ImportError("[CWE-758] Failed to import context") from None else: from context import unittest from context import os as _os from context import sys as _sys -except Exception: # pragma: no branch - raise ImportError("[CWE-758] Failed to import test context") +except Exception as _cause: # pragma: no branch + raise ImportError("[CWE-758] Failed to import test context") from _cause try: if 're' not in _sys.modules: import re else: # pragma: no branch re = _sys.modules["""re"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] re Failed to import.") +except Exception as _cause: # pragma: no branch + raise ImportError("[CWE-440] re Failed to import.") from _cause try: if 'venv' not in _sys.modules: import venv else: # pragma: no branch venv = _sys.modules["""venv"""] -except Exception: # pragma: no branch - raise ImportError("[CWE-440] venv Failed to import.") +except Exception as _cause: # pragma: no branch + raise ImportError("[CWE-440] venv Failed to import.") from _cause class TestRequirementsTxt(context.BasicUsageTestSuite): diff --git a/tests/test_install_requires.py b/tests/test_install_requires.py index 831a4591..278631a2 100644 --- a/tests/test_install_requires.py +++ b/tests/test_install_requires.py @@ -28,15 +28,15 @@ del ImportErr # skipcq - cleanup any error leaks early from . import context if context.__name__ is None: - raise ImportError("[CWE-758] Failed to import context") + raise ImportError("[CWE-758] Failed to import context") from None else: from context import unittest from context import os as _os from context import BasicUsageTestSuite from setup import readFile from setup import parse_requirements_for_install_requires -except Exception: # pragma: no branch - raise ImportError("[CWE-758] Failed to import test context") +except Exception as _cause: # pragma: no branch + raise ImportError("[CWE-758] Failed to import test context") from _cause class TestParseRequirements(BasicUsageTestSuite): diff --git a/tests/test_manifest.py b/tests/test_manifest.py index 19b847dd..e98e2bfa 100644 --- a/tests/test_manifest.py +++ b/tests/test_manifest.py @@ -28,7 +28,7 @@ del ImportErr # skipcq - cleanup any error leaks early from . import context if context.__name__ is None: - raise ImportError("[CWE-758] Failed to import context") + raise ImportError("[CWE-758] Failed to import context") from None else: from context import unittest from context import subprocess @@ -36,8 +36,8 @@ from context import sys as _sys from context import BasicUsageTestSuite import tarfile -except Exception: # pragma: no branch - raise ImportError("[CWE-758] Failed to import test context") +except Exception as _cause: # pragma: no branch + raise ImportError("[CWE-758] Failed to import test context") from _cause class TestManifestInclusion(BasicUsageTestSuite): diff --git a/tests/test_usage.py b/tests/test_usage.py index 6c2c7410..59bd925a 100644 --- a/tests/test_usage.py +++ b/tests/test_usage.py @@ -50,9 +50,9 @@ try: import sys if sys.__name__ is None: # pragma: no branch - raise ImportError("[CWE-440] OMG! we could not import sys! ABORT. ABORT.") + raise ModuleNotFoundError("[CWE-440] OMG! we could not import sys! ABORT. ABORT.") from None except Exception as err: # pragma: no branch - raise ImportError(err) + raise ImportError(err) from err try: @@ -63,15 +63,15 @@ del ImportErr # skipcq - cleanup any error leaks early from . import context if context.__name__ is None: - raise ImportError("[CWE-758] Failed to import context") + raise ModuleNotFoundError("[CWE-758] Failed to import context") from None else: from context import multicast # pylint: disable=cyclic-import - skipcq: PYL-R0401 from context import unittest from context import subprocess from context import Process import random as _random -except Exception: - raise ImportError("[CWE-758] Failed to import test context") +except Exception as err: + raise ImportError("[CWE-758] Failed to import test context") from err class MulticastTestSuite(context.BasicUsageTestSuite): @@ -329,9 +329,9 @@ def test_hear_works_WHEN_say_works(self): self.assertIsNotNone( multicast.__main__.McastDispatch().doStep("SAY", _fixture_SAY_args) ) - except Exception: + except Exception as _cause: p.join() - raise unittest.SkipTest(fail_fixture) + raise unittest.SkipTest(fail_fixture) from _cause p.join() self.assertIsNotNone(p.exitcode) self.assertEqual(int(p.exitcode), int(0)) @@ -380,9 +380,9 @@ def test_hear_works_WHEN_fuzzed_and_say_works(self): self.assertIsNotNone( multicast.__main__.McastDispatch().doStep("SAY", _fixture_SAY_args) ) - except Exception: + except Exception as _cause: p.join() - raise unittest.SkipTest(fail_fixture) + raise unittest.SkipTest(fail_fixture) from _cause p.join() self.assertIsNotNone(p.exitcode) self.assertEqual(int(p.exitcode), int(0)) @@ -416,9 +416,9 @@ def test_recv_Errors_WHEN_say_not_used(self): tuple((int(2), "NoOp")), # skipcq: PTC-W0020 - This is test-code. sub_fail_fixture ) - except Exception: + except Exception as _cause: p.join() - raise unittest.SkipTest(sub_fail_fixture) + raise unittest.SkipTest(sub_fail_fixture) from _cause p.join() self.assertIsNotNone(p.exitcode, fail_fixture) self.assertEqual(int(p.exitcode), int(0))