diff --git a/securesystemslib/__init__.py b/securesystemslib/__init__.py index 19dcaece..95b143cb 100755 --- a/securesystemslib/__init__.py +++ b/securesystemslib/__init__.py @@ -1,3 +1,4 @@ +# pylint: disable=missing-module-docstring import logging # Configure a basic 'securesystemslib' top-level logger with a StreamHandler diff --git a/securesystemslib/ecdsa_keys.py b/securesystemslib/ecdsa_keys.py index 8e4e55e1..65098f39 100755 --- a/securesystemslib/ecdsa_keys.py +++ b/securesystemslib/ecdsa_keys.py @@ -52,7 +52,10 @@ CRYPTO = False # Perform object format-checking and add ability to handle/raise exceptions. -from securesystemslib import exceptions, formats +from securesystemslib import ( # pylint: disable=wrong-import-position + exceptions, + formats, +) _SUPPORTED_ECDSA_SCHEMES = ["ecdsa-sha2-nistp256"] @@ -324,7 +327,9 @@ def verify_signature(public_key, scheme, signature, data): f"Failed to load PEM key {public_key}" ) from e - if not isinstance(ecdsa_key, ec.EllipticCurvePublicKey): + if not isinstance( # pylint: disable=no-else-raise + ecdsa_key, ec.EllipticCurvePublicKey + ): raise exceptions.FormatError( "Invalid ECDSA public" " key: " + repr(public_key) ) diff --git a/securesystemslib/ed25519_keys.py b/securesystemslib/ed25519_keys.py index ca4fff1c..2397043e 100755 --- a/securesystemslib/ed25519_keys.py +++ b/securesystemslib/ed25519_keys.py @@ -71,6 +71,7 @@ except ImportError: NACL = False +# pylint: disable=wrong-import-position from securesystemslib import exceptions, formats # The optimized pure Python implementation of Ed25519. If @@ -78,6 +79,8 @@ # 'securesystemslib.exceptions.UnsupportedLibraryError' exception is raised. from securesystemslib._vendor.ed25519 import ed25519 as python_ed25519 +# pylint: enable=wrong-import-position + # Supported ed25519 signing schemes: 'ed25519'. The pure Python implementation # (i.e., ed25519') and PyNaCl (i.e., 'nacl', libsodium + Python bindings) # modules are currently supported in the creation of 'ed25519' signatures. @@ -332,7 +335,7 @@ def verify_signature(public_key, scheme, signature, data): # The pure Python implementation raises 'Exception' if 'signature' is # invalid. - except Exception: + except Exception: # pylint: disable=broad-except pass # This is a defensive check for a valid 'scheme', which should have already diff --git a/securesystemslib/exceptions.py b/securesystemslib/exceptions.py index 064c9a56..2ace2679 100755 --- a/securesystemslib/exceptions.py +++ b/securesystemslib/exceptions.py @@ -21,25 +21,25 @@ class Error(Exception): """Indicate a generic error.""" - pass + pass # pylint: disable=unnecessary-pass -class Warning(Warning): +class Warning(Warning): # pylint: disable=redefined-builtin """Generic warning. It is used by the 'warnings' module.""" - pass + pass # pylint: disable=unnecessary-pass class FormatError(Error): """Indicate an error while validating an object's format.""" - pass + pass # pylint: disable=unnecessary-pass class InvalidMetadataJSONError(FormatError): """Indicate that a metadata file is not valid JSON.""" - def __init__(self, exception): + def __init__(self, exception): # pylint: disable=super-init-not-called # Store the original exception. self.exception = exception @@ -51,13 +51,15 @@ def __str__(self): class UnsupportedAlgorithmError(Error): """Indicate an error while trying to identify a user-specified algorithm.""" - pass + pass # pylint: disable=unnecessary-pass class BadHashError(Error): """Indicate an error while checking the value a hash object.""" - def __init__(self, expected_hash, observed_hash): + def __init__( + self, expected_hash, observed_hash + ): # pylint: disable=super-init-not-called self.expected_hash = expected_hash self.observed_hash = observed_hash @@ -74,19 +76,21 @@ def __str__(self): class BadPasswordError(Error): """Indicate an error after encountering an invalid password.""" - pass + pass # pylint: disable=unnecessary-pass class CryptoError(Error): """Indicate any cryptography-related errors.""" - pass + pass # pylint: disable=unnecessary-pass class BadSignatureError(CryptoError): """Indicate that some metadata has a bad signature.""" - def __init__(self, metadata_role_name): + def __init__( + self, metadata_role_name + ): # pylint: disable=super-init-not-called self.metadata_role_name = metadata_role_name def __str__(self): @@ -96,41 +100,41 @@ def __str__(self): class UnknownMethodError(CryptoError): """Indicate that a user-specified cryptograpthic method is unknown.""" - pass + pass # pylint: disable=unnecessary-pass class UnsupportedLibraryError(Error): """Indicate that a supported library could not be located or imported.""" - pass + pass # pylint: disable=unnecessary-pass class InvalidNameError(Error): """Indicate an error while trying to validate any type of named object.""" - pass + pass # pylint: disable=unnecessary-pass class NotFoundError(Error): """If a required configuration or resource is not found.""" - pass + pass # pylint: disable=unnecessary-pass class URLMatchesNoPatternError(Error): """If a URL does not match a user-specified regular expression.""" - pass + pass # pylint: disable=unnecessary-pass class InvalidConfigurationError(Error): """If a configuration object does not match the expected format.""" - pass + pass # pylint: disable=unnecessary-pass class StorageError(Error): """Indicate an error occured during interaction with an abstracted storage backend.""" - pass + pass # pylint: disable=unnecessary-pass diff --git a/securesystemslib/formats.py b/securesystemslib/formats.py index 1ceee9bc..ad1f07c7 100755 --- a/securesystemslib/formats.py +++ b/securesystemslib/formats.py @@ -334,7 +334,7 @@ def _create_gpg_pubkey_with_subkey_schema(pubkey_schema): # define the attributes of the object in its `_required` property, even if # such a schema is of type `Optional`. # TODO: Find a way that does not require to access a protected member - schema._required.append( + schema._required.append( # pylint: disable=protected-access subkey_schema_tuple ) # pylint: disable=protected-access return schema @@ -640,7 +640,9 @@ def _canonical_string_encoder(string): return string -def _encode_canonical(object, output_function): +def _encode_canonical( + object, output_function +): # pylint: disable=missing-function-docstring,redefined-builtin # Helper for encode_canonical. Older versions of json.encoder don't # even let us replace the separators. @@ -680,7 +682,9 @@ def _encode_canonical(object, output_function): raise exceptions.FormatError("I cannot encode " + repr(object)) -def encode_canonical(object, output_function=None): +def encode_canonical( # pylint: disable=inconsistent-return-statements + object, output_function=None # pylint: disable=redefined-builtin +): """ Encode 'object' in canonical JSON form, as specified at diff --git a/securesystemslib/gpg/common.py b/securesystemslib/gpg/common.py index 2ae9c575..9d8c4d8f 100644 --- a/securesystemslib/gpg/common.py +++ b/securesystemslib/gpg/common.py @@ -104,7 +104,7 @@ def parse_pubkey_payload(data): ptr += 1 if version_number not in SUPPORTED_PUBKEY_PACKET_VERSIONS: raise PacketVersionNotSupportedError( - "Pubkey packet version '{}' not supported, must be one of {}".format( + "Pubkey packet version '{}' not supported, must be one of {}".format( # pylint: disable=consider-using-f-string version_number, SUPPORTED_PUBKEY_PACKET_VERSIONS ) ) @@ -129,7 +129,7 @@ def parse_pubkey_payload(data): # as described in section 5.2.3.21. if algorithm not in SUPPORTED_SIGNATURE_ALGORITHMS: raise SignatureAlgorithmNotSupportedError( - "Signature algorithm '{}' not " + "Signature algorithm '{}' not " # pylint: disable=consider-using-f-string "supported, please verify that your gpg configuration is creating " "either DSA, RSA, or EdDSA signatures (see RFC4880 9.1. Public-Key " "Algorithms).".format(algorithm) @@ -210,12 +210,12 @@ def parse_pubkey_bundle(data): # - there must be least one User ID packet, or # - order and type of signatures, or # - disallow duplicate packets - if ( + if ( # pylint: disable=no-else-raise packet_type != PACKET_TYPE_PRIMARY_KEY and not key_bundle[PACKET_TYPE_PRIMARY_KEY]["key"] ): raise PacketParsingError( - "First packet must be a primary key ('{}'), " + "First packet must be a primary key ('{}'), " # pylint: disable=consider-using-f-string "got '{}'.".format(PACKET_TYPE_PRIMARY_KEY, packet_type) ) @@ -281,7 +281,7 @@ def parse_pubkey_bundle(data): else: log.info( - "Ignoring gpg key packet '{}', we only handle packets of " + "Ignoring gpg key packet '{}', we only handle packets of " # pylint: disable=logging-format-interpolation,consider-using-f-string "types '{}' (see RFC4880 4.3. Packet Tags).".format( packet_type, [ @@ -296,8 +296,8 @@ def parse_pubkey_bundle(data): # Both errors might be raised in parse_packet_header and in this loop except (PacketParsingError, IndexError) as e: - raise PacketParsingError( - "Invalid public key data at position {}: {}.".format( + raise PacketParsingError( # pylint: disable=raise-missing-from + "Invalid public key data at position {}: {}.".format( # pylint: disable=consider-using-f-string position, e ) ) @@ -368,7 +368,7 @@ def _assign_certified_key_info(bundle): # TODO: Revise exception taxonomy: # It's okay to ignore some exceptions (unsupported algorithms etc.) but # we should blow up if a signature is malformed (missing subpackets). - except Exception as e: + except Exception as e: # pylint: disable=broad-except log.info(e) continue @@ -376,7 +376,7 @@ def _assign_certified_key_info(bundle): signature["keyid"] ): log.info( - "Ignoring User ID certificate issued by '{}'.".format( + "Ignoring User ID certificate issued by '{}'.".format( # pylint: disable=logging-format-interpolation,consider-using-f-string signature["keyid"] ) ) @@ -391,7 +391,7 @@ def _assign_certified_key_info(bundle): if not is_valid: log.info( - "Ignoring invalid User ID self-certificate issued " + "Ignoring invalid User ID self-certificate issued " # pylint: disable=logging-format-interpolation,consider-using-f-string "by '{}'.".format(signature["keyid"]) ) continue @@ -493,7 +493,7 @@ def _get_verified_subkeys(bundle): ) # TODO: Revise exception taxonomy - except Exception as e: + except Exception as e: # pylint: disable=broad-except log.info(e) continue @@ -523,7 +523,7 @@ def _get_verified_subkeys(bundle): key_binding_signatures.append(signature) # TODO: Revise exception taxonomy - except Exception as e: + except Exception as e: # pylint: disable=broad-except log.info(e) continue # NOTE: As per the V4 key structure diagram in RFC4880 section 12.1., a @@ -535,7 +535,7 @@ def _get_verified_subkeys(bundle): # an *embedded primary key binding signature*. if len(key_binding_signatures) != 1: log.info( - "Ignoring subkey '{}' due to wrong amount of key binding " + "Ignoring subkey '{}' due to wrong amount of key binding " # pylint: disable=logging-format-interpolation,consider-using-f-string "signatures ({}), must be exactly 1.".format( subkey["keyid"], len(key_binding_signatures) ) @@ -550,7 +550,7 @@ def _get_verified_subkeys(bundle): if not is_valid: log.info( - "Ignoring subkey '{}' due to invalid key binding signature.".format( + "Ignoring subkey '{}' due to invalid key binding signature.".format( # pylint: disable=logging-format-interpolation,consider-using-f-string subkey["keyid"] ) ) @@ -615,7 +615,7 @@ def get_pubkey_bundle(data, keyid): formats.KEYID_SCHEMA.check_match(keyid) if not data: raise KeyNotFoundError( - "Could not find gpg key '{}' in empty exported key " + "Could not find gpg key '{}' in empty exported key " # pylint: disable=consider-using-f-string "data.".format(keyid) ) @@ -636,7 +636,7 @@ def get_pubkey_bundle(data, keyid): if public_key and public_key["keyid"].endswith(keyid.lower()): if idx > 1: log.warning( - "Exporting master key '{}' including subkeys '{}' for" + "Exporting master key '{}' including subkeys '{}' for" # pylint: disable=logging-format-interpolation,consider-using-f-string " passed keyid '{}'.".format( master_public_key["keyid"], ", ".join(list(sub_public_keys.keys())), @@ -647,7 +647,9 @@ def get_pubkey_bundle(data, keyid): else: raise KeyNotFoundError( - "Could not find gpg key '{}' in exported key data.".format(keyid) + "Could not find gpg key '{}' in exported key data.".format( # pylint: disable=consider-using-f-string + keyid + ) ) # Add subkeys dictionary to master pubkey "subkeys" field if subkeys exist @@ -657,7 +659,7 @@ def get_pubkey_bundle(data, keyid): return master_public_key -def parse_signature_packet( +def parse_signature_packet( # pylint: disable=too-many-locals,too-many-branches,too-many-statements data, supported_signature_types=None, supported_hash_algorithms=None, @@ -729,7 +731,7 @@ def parse_signature_packet( ptr += 1 if version_number not in SUPPORTED_SIGNATURE_PACKET_VERSIONS: raise ValueError( - "Signature version '{}' not supported, must be one of " + "Signature version '{}' not supported, must be one of " # pylint: disable=consider-using-f-string "{}.".format(version_number, SUPPORTED_SIGNATURE_PACKET_VERSIONS) ) @@ -742,7 +744,7 @@ def parse_signature_packet( if signature_type not in supported_signature_types: raise ValueError( - "Signature type '{}' not supported, must be one of {} " + "Signature type '{}' not supported, must be one of {} " # pylint: disable=consider-using-f-string "(see RFC4880 5.2.1. Signature Types).".format( signature_type, supported_signature_types ) @@ -753,7 +755,7 @@ def parse_signature_packet( if signature_algorithm not in SUPPORTED_SIGNATURE_ALGORITHMS: raise ValueError( - "Signature algorithm '{}' not " + "Signature algorithm '{}' not " # pylint: disable=consider-using-f-string "supported, please verify that your gpg configuration is creating " "either DSA, RSA, or EdDSA signatures (see RFC4880 9.1. Public-Key " "Algorithms).".format(signature_algorithm) @@ -767,7 +769,7 @@ def parse_signature_packet( if hash_algorithm not in supported_hash_algorithms: raise ValueError( - "Hash algorithm '{}' not supported, must be one of {}" + "Hash algorithm '{}' not supported, must be one of {}" # pylint: disable=consider-using-f-string " (see RFC4880 9.4. Hash Algorithms).".format( hash_algorithm, supported_hash_algorithms ) @@ -868,7 +870,7 @@ def parse_signature_packet( # Fail if keyid and short keyid are specified but don't match if keyid and not keyid.endswith(short_keyid): # pragma: no cover raise ValueError( - "This signature packet seems to be corrupted. The key ID " + "This signature packet seems to be corrupted. The key ID " # pylint: disable=consider-using-f-string "'{}' of the 'Issuer' subpacket must match the lower 64 bits of the " "fingerprint '{}' of the 'Issuer Fingerprint' subpacket (see RFC4880 " "and rfc4880bis-06 5.2.3.28. Issuer Fingerprint).".format( @@ -892,7 +894,7 @@ def parse_signature_packet( signature = handler.get_signature_params(data[ptr:]) signature_data = { - "keyid": "{}".format(keyid), + "keyid": "{}".format(keyid), # pylint: disable=consider-using-f-string "other_headers": binascii.hexlify(data[:other_headers_ptr]).decode( "ascii" ), diff --git a/securesystemslib/gpg/dsa.py b/securesystemslib/gpg/dsa.py index e491f769..979b8381 100644 --- a/securesystemslib/gpg/dsa.py +++ b/securesystemslib/gpg/dsa.py @@ -26,10 +26,13 @@ except ImportError: CRYPTO = False +# pylint: disable=wrong-import-position from securesystemslib import exceptions, formats from securesystemslib.gpg import util as gpg_util from securesystemslib.gpg.exceptions import PacketParsingError +# pylint: enable=wrong-import-position + def create_pubkey(pubkey_info): """ diff --git a/securesystemslib/gpg/eddsa.py b/securesystemslib/gpg/eddsa.py index 8d906417..a052f398 100644 --- a/securesystemslib/gpg/eddsa.py +++ b/securesystemslib/gpg/eddsa.py @@ -79,7 +79,7 @@ def get_pubkey_params(data): # See 9.2. ECC Curve OID if curve_oid != ED25519_PUBLIC_KEY_OID: raise PacketParsingError( - "bad ed25519 curve OID '{}', expected {}'".format( + "bad ed25519 curve OID '{}', expected {}'".format( # pylint: disable=consider-using-f-string curve_oid, ED25519_PUBLIC_KEY_OID ) ) @@ -90,7 +90,7 @@ def get_pubkey_params(data): if public_key_len != ED25519_PUBLIC_KEY_LENGTH: raise PacketParsingError( - "bad ed25519 MPI length '{}', expected {}'".format( + "bad ed25519 MPI length '{}', expected {}'".format( # pylint: disable=consider-using-f-string public_key_len, ED25519_PUBLIC_KEY_LENGTH ) ) @@ -100,7 +100,7 @@ def get_pubkey_params(data): if public_key_prefix != ED25519_PUBLIC_KEY_PREFIX: raise PacketParsingError( - "bad ed25519 MPI prefix '{}', expected '{}'".format( + "bad ed25519 MPI prefix '{}', expected '{}'".format( # pylint: disable=consider-using-f-string public_key_prefix, ED25519_PUBLIC_KEY_PREFIX ) ) diff --git a/securesystemslib/gpg/exceptions.py b/securesystemslib/gpg/exceptions.py index 13049a59..695bba94 100644 --- a/securesystemslib/gpg/exceptions.py +++ b/securesystemslib/gpg/exceptions.py @@ -41,9 +41,11 @@ class CommandError(Exception): pass -class KeyExpirationError(Exception): +class KeyExpirationError(Exception): # pylint: disable=missing-class-docstring def __init__(self, key): - super(KeyExpirationError, self).__init__() + super( # pylint: disable=super-with-arguments + KeyExpirationError, self + ).__init__() self.key = key def __str__(self): @@ -56,7 +58,7 @@ def __str__(self): validity_period = expiration_time - creation_time return ( - "GPG key '{}' created on '{:%Y-%m-%d %H:%M} UTC' with validity " + "GPG key '{}' created on '{:%Y-%m-%d %H:%M} UTC' with validity " # pylint: disable=consider-using-f-string "period '{}' expired on '{:%Y-%m-%d %H:%M} UTC'.".format( self.key["keyid"], creation_time, diff --git a/securesystemslib/gpg/functions.py b/securesystemslib/gpg/functions.py index 3b3204ba..c299bea1 100644 --- a/securesystemslib/gpg/functions.py +++ b/securesystemslib/gpg/functions.py @@ -105,11 +105,19 @@ def create_signature(content, keyid=None, homedir=None): keyarg = "" if keyid: formats.KEYID_SCHEMA.check_match(keyid) - keyarg = "--local-user {}".format(keyid) + keyarg = ( + "--local-user {}".format( # pylint: disable=consider-using-f-string + keyid + ) + ) homearg = "" if homedir: - homearg = "--homedir {}".format(homedir).replace("\\", "/") + homearg = ( + "--homedir {}".format( # pylint: disable=consider-using-f-string + homedir + ).replace("\\", "/") + ) command = gpg_sign_command(keyarg=keyarg, homearg=homearg) @@ -126,7 +134,7 @@ def create_signature(content, keyid=None, homedir=None): # https://lists.gnupg.org/pipermail/gnupg-devel/2005-December/022559.html if gpg_process.returncode != 0: raise CommandError( - "Command '{}' returned " + "Command '{}' returned " # pylint: disable=consider-using-f-string "non-zero exit status '{}', stderr was:\n{}.".format( gpg_process.args, gpg_process.returncode, @@ -146,7 +154,7 @@ def create_signature(content, keyid=None, homedir=None): # test environments. if not signature["keyid"]: # pragma: no cover log.warning( - "The created signature does not include the hashed subpacket" + "The created signature does not include the hashed subpacket" # pylint: disable=logging-format-interpolation,consider-using-f-string " '33' (full keyid). You probably have a gpg version <{}." " We will export the public keys associated with the short keyid to" " compute the full keyid.".format(FULLY_SUPPORTED_MIN_VERSION) @@ -175,7 +183,7 @@ def create_signature(content, keyid=None, homedir=None): # If there is still no full keyid something went wrong if not signature["keyid"]: # pragma: no cover raise ValueError( - "Full keyid could not be determined for signature '{}'".format( + "Full keyid could not be determined for signature '{}'".format( # pylint: disable=consider-using-f-string signature ) ) @@ -284,13 +292,17 @@ def export_pubkey(keyid, homedir=None): # FIXME: probably needs smarter parsing of what a valid keyid is so as to # not export more than one pubkey packet. raise ValueError( - "we need to export an individual key. Please provide a " + "we need to export an individual key. Please provide a " # pylint: disable=consider-using-f-string " valid keyid! Keyid was '{}'.".format(keyid) ) homearg = "" if homedir: - homearg = "--homedir {}".format(homedir).replace("\\", "/") + homearg = ( + "--homedir {}".format( # pylint: disable=consider-using-f-string + homedir + ).replace("\\", "/") + ) # TODO: Consider adopting command error handling from `create_signature` # above, e.g. in a common 'run gpg command' utility function diff --git a/securesystemslib/gpg/rsa.py b/securesystemslib/gpg/rsa.py index 5620b1c9..ed28f875 100644 --- a/securesystemslib/gpg/rsa.py +++ b/securesystemslib/gpg/rsa.py @@ -25,10 +25,13 @@ except ImportError: CRYPTO = False +# pylint: disable=wrong-import-position from securesystemslib import exceptions, formats from securesystemslib.gpg import util as gpg_util from securesystemslib.gpg.exceptions import PacketParsingError +# pylint: enable=wrong-import-position + def create_pubkey(pubkey_info): """ @@ -199,7 +202,9 @@ def verify_signature(signature_object, pubkey_info, content, hash_algorithm_id): signature_length = len(signature_object["signature"]) if pubkey_length != signature_length: # pragma: no cover zero_pad = "0" * (pubkey_length - signature_length) - signature_object["signature"] = "{}{}".format( + signature_object[ + "signature" + ] = "{}{}".format( # pylint: disable=consider-using-f-string zero_pad, signature_object["signature"] ) diff --git a/securesystemslib/gpg/util.py b/securesystemslib/gpg/util.py index b8a04fc5..6aa7cbc6 100644 --- a/securesystemslib/gpg/util.py +++ b/securesystemslib/gpg/util.py @@ -101,7 +101,9 @@ def hash_object(headers, algorithm, content): return hasher.finalize() -def parse_packet_header(data, expected_type=None): +def parse_packet_header( + data, expected_type=None +): # pylint: disable=too-many-branches """ Parse out packet type and header and body lengths from an RFC4880 packet. @@ -205,7 +207,7 @@ def parse_packet_header(data, expected_type=None): if expected_type is not None and packet_type != expected_type: raise PacketParsingError( - "Expected packet " + "Expected packet " # pylint: disable=consider-using-f-string "{}, but got {} instead!".format(expected_type, packet_type) ) @@ -446,8 +448,8 @@ def get_hashing_class(hash_algorithm_id): return hashing_class[hash_algorithm_id] except KeyError: - raise ValueError( - "Hash algorithm '{}' not supported, must be one of '{}' " + raise ValueError( # pylint: disable=raise-missing-from + "Hash algorithm '{}' not supported, must be one of '{}' " # pylint: disable=consider-using-f-string "(see RFC4880 9.4. Hash Algorithms).".format( hash_algorithm_id, supported_hashing_algorithms ) diff --git a/securesystemslib/hash.py b/securesystemslib/hash.py index 6119f738..4ea04e17 100755 --- a/securesystemslib/hash.py +++ b/securesystemslib/hash.py @@ -52,7 +52,9 @@ SUPPORTED_LIBRARIES.append("pyca_crypto") - class PycaDiggestWrapper(object): + class PycaDiggestWrapper( + object + ): # pylint: disable=useless-object-inheritance """ A wrapper around `cryptography.hazmat.primitives.hashes.Hash` which adds @@ -99,7 +101,9 @@ def digest_size(self): def digest(self): digest_obj_copy = self._digest_obj.copy() - digest = self._digest_obj.finalize() + digest = ( # pylint: disable=redefined-outer-name + self._digest_obj.finalize() + ) self._digest_obj = digest_obj_copy return digest @@ -175,7 +179,7 @@ def digest(algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY): # If so, return the digest object. if hash_library == "hashlib" and hash_library in SUPPORTED_LIBRARIES: try: - if algorithm == "blake2b-256": + if algorithm == "blake2b-256": # pylint: disable=no-else-return return hashlib.new("blake2b", digest_size=32) else: return hashlib.new(algorithm) @@ -183,7 +187,9 @@ def digest(algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY): except (ValueError, TypeError): # ValueError: the algorithm value was unknown # TypeError: unexpected argument digest_size (on old python) - raise exceptions.UnsupportedAlgorithmError(algorithm) + raise exceptions.UnsupportedAlgorithmError( # pylint: disable=raise-missing-from + algorithm + ) # Was a pyca_crypto digest object requested and is it supported? elif hash_library == "pyca_crypto" and hash_library in SUPPORTED_LIBRARIES: @@ -194,7 +200,9 @@ def digest(algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY): ) except KeyError: - raise exceptions.UnsupportedAlgorithmError(algorithm) + raise exceptions.UnsupportedAlgorithmError( # pylint: disable=raise-missing-from + algorithm + ) # The requested hash library is not supported. else: diff --git a/securesystemslib/interface.py b/securesystemslib/interface.py index 9a3b1464..4238bfdb 100644 --- a/securesystemslib/interface.py +++ b/securesystemslib/interface.py @@ -84,7 +84,7 @@ def get_password(prompt="Password: ", confirm=False): return password password2 = getpass.getpass("Confirm: ", sys.stderr) - if password == password2: + if password == password2: # pylint: disable=no-else-return return password else: @@ -122,7 +122,7 @@ def _get_key_file_encryption_password(password, prompt, path): # Treat empty password as no password. A user on the prompt can only # indicate the desire to not encrypt by entering no password. - if not len(password): + if not len(password): # pylint: disable=use-implicit-booleaness-not-len return None if password is not None: @@ -130,7 +130,7 @@ def _get_key_file_encryption_password(password, prompt, path): # Fail on empty passed password. A caller should pass None to indicate the # desire to not encrypt. - if not len(password): + if not len(password): # pylint: disable=use-implicit-booleaness-not-len raise ValueError( "encryption password must be 1 or more characters long" ) @@ -169,7 +169,7 @@ def _get_key_file_decryption_password(password, prompt, path): # Treat empty password as no password. A user on the prompt can only # indicate the desire to not decrypt by entering no password. - if not len(password): + if not len(password): # pylint: disable=use-implicit-booleaness-not-len return None if password is not None: @@ -1004,7 +1004,7 @@ def import_publickeys_from_file(filepaths, key_types=None): if len(key_types) != len(filepaths): raise exceptions.FormatError( - "Pass equal amount of 'filepaths' (got {}) and 'key_types (got {}), " + "Pass equal amount of 'filepaths' (got {}) and 'key_types (got {}), " # pylint: disable=consider-using-f-string "or no 'key_types' at all to default to '{}'.".format( len(filepaths), len(key_types), KEY_TYPE_RSA ) @@ -1023,7 +1023,7 @@ def import_publickeys_from_file(filepaths, key_types=None): else: raise exceptions.FormatError( - "Unsupported key type '{}'. Must be '{}', '{}' or '{}'.".format( + "Unsupported key type '{}'. Must be '{}', '{}' or '{}'.".format( # pylint: disable=consider-using-f-string key_types[idx], KEY_TYPE_RSA, KEY_TYPE_ED25519, @@ -1073,7 +1073,7 @@ def import_privatekey_from_file( if key_type is None: key_type = KEY_TYPE_RSA - if key_type == KEY_TYPE_ED25519: + if key_type == KEY_TYPE_ED25519: # pylint: disable=no-else-return return import_ed25519_privatekey_from_file( filepath, password=password, prompt=prompt ) @@ -1090,7 +1090,7 @@ def import_privatekey_from_file( else: raise exceptions.FormatError( - "Unsupported key type '{}'. Must be '{}', '{}' or '{}'.".format( + "Unsupported key type '{}'. Must be '{}', '{}' or '{}'.".format( # pylint: disable=consider-using-f-string key_type, KEY_TYPE_RSA, KEY_TYPE_ED25519, KEY_TYPE_ECDSA ) ) diff --git a/securesystemslib/keys.py b/securesystemslib/keys.py index 3f0ce85f..940f97a5 100755 --- a/securesystemslib/keys.py +++ b/securesystemslib/keys.py @@ -426,7 +426,7 @@ def format_keyval_to_metadata(keytype, scheme, key_value, private=False): # key in the returned dictionary, ensure the private key is actually # present in 'key_val' (a private key is optional for 'KEYVAL_SCHEMA' # dicts). - if "private" not in key_value: + if "private" not in key_value: # pylint: disable=no-else-raise raise exceptions.FormatError( "The required private key" " is missing from: " + repr(key_value) @@ -710,7 +710,9 @@ def create_signature(key_dict, data): return signature -def verify_signature(key_dict, signature, data): +def verify_signature( + key_dict, signature, data +): # pylint: disable=too-many-branches """ Determine whether the private key belonging to 'key_dict' produced @@ -795,7 +797,7 @@ def verify_signature(key_dict, signature, data): # Verify that the KEYID in 'key_dict' matches the KEYID listed in the # 'signature'. - if key_dict["keyid"] != signature["keyid"]: + if key_dict["keyid"] != signature["keyid"]: # pylint: disable=no-else-raise raise exceptions.CryptoError( "The KEYID (" " " + repr(key_dict["keyid"]) + " ) in the given key does not match" @@ -1191,15 +1193,15 @@ def extract_pem(pem, private_pem=False): except ValueError: # Be careful not to print private key material in exception message. - if not private_pem: - raise exceptions.FormatError( + if not private_pem: # pylint: disable=no-else-raise + raise exceptions.FormatError( # pylint: disable=raise-missing-from "Required PEM" " header " + repr(pem_header) + "\n not found in PEM" " string: " + repr(pem) ) else: - raise exceptions.FormatError( + raise exceptions.FormatError( # pylint: disable=raise-missing-from "Required PEM" " header " + repr(pem_header) @@ -1212,15 +1214,15 @@ def extract_pem(pem, private_pem=False): except ValueError: # Be careful not to print private key material in exception message. - if not private_pem: - raise exceptions.FormatError( + if not private_pem: # pylint: disable=no-else-raise + raise exceptions.FormatError( # pylint: disable=raise-missing-from "Required PEM" " footer " + repr(pem_footer) + "\n not found in PEM" " string " + repr(pem) ) else: - raise exceptions.FormatError( + raise exceptions.FormatError( # pylint: disable=raise-missing-from "Required PEM" " footer " + repr(pem_footer) @@ -1555,7 +1557,9 @@ def is_pem_private(pem, keytype="rsa"): return True -def import_ed25519key_from_private_json(json_str, password=None): +def import_ed25519key_from_private_json( + json_str, password=None +): # pylint: disable=missing-function-docstring if password is not None: # This check will not fail, because a mal-formatted passed password fails # above and an entered password will always be a string (see get_password) @@ -1577,7 +1581,7 @@ def import_ed25519key_from_private_json(json_str, password=None): # If the JSON could not be decoded, it is very likely, but not necessarily, # due to a non-empty password. except exceptions.Error: - raise exceptions.CryptoError( + raise exceptions.CryptoError( # pylint: disable=raise-missing-from "Malformed Ed25519 key JSON, " "possibly due to encryption, " "but no password provided?" diff --git a/securesystemslib/process.py b/securesystemslib/process.py index 6f06ff25..7232e256 100644 --- a/securesystemslib/process.py +++ b/securesystemslib/process.py @@ -113,7 +113,7 @@ def run(cmd, check=True, timeout=_default_timeout(), **kwargs): # don't pass on `stdin` if the user passes `input` and `stdin` # https://github.com/python/cpython/blob/3.5/Lib/subprocess.py#L378-L381 if kwargs.get("input") is not None and "stdin" in kwargs: - log.debug( + log.debug( # pylint: disable=logging-not-lazy "stdin and input arguments may not both be used. " "Ignoring passed stdin: " + str(kwargs["stdin"]) ) @@ -174,16 +174,18 @@ def run_duplicate_streams(cmd, timeout=_default_timeout()): stdout_fd, stdout_name = tempfile.mkstemp() stderr_fd, stderr_name = tempfile.mkstemp() try: - with io.open(stdout_name, "r") as stdout_reader, os.fdopen( + with io.open( # pylint: disable=unspecified-encoding + stdout_name, "r" + ) as stdout_reader, os.fdopen( # pylint: disable=unspecified-encoding stdout_fd, "w" - ) as stdout_writer, io.open( + ) as stdout_writer, io.open( # pylint: disable=unspecified-encoding stderr_name, "r" ) as stderr_reader, os.fdopen( stderr_fd, "w" ) as stderr_writer: # Store stream results in mutable dict to update it inside nested helper - _std = {"out": "", "err": ""} + _std = {"out": "", "err": ""} # pylint: disable=invalid-name def _duplicate_streams(): """Helper to read from child process standard streams, write their @@ -203,7 +205,7 @@ def _duplicate_streams(): _std["err"] += stderr_part # Start child process, writing its standard streams to temporary files - proc = subprocess.Popen( + proc = subprocess.Popen( # pylint: disable=consider-using-with cmd, stdout=stdout_writer, stderr=stderr_writer, diff --git a/securesystemslib/rsa_keys.py b/securesystemslib/rsa_keys.py index 67a79f40..a567ef8c 100755 --- a/securesystemslib/rsa_keys.py +++ b/securesystemslib/rsa_keys.py @@ -107,8 +107,15 @@ except ImportError: CRYPTO = False -from securesystemslib import exceptions, formats, settings, util -from securesystemslib.hash import digest_from_rsa_scheme +from securesystemslib import ( # pylint: disable=wrong-import-position + exceptions, + formats, + settings, + util, +) +from securesystemslib.hash import ( # pylint: disable=wrong-import-position + digest_from_rsa_scheme, +) # Recommended RSA key sizes: # http://www.emc.com/emc-plus/rsa-labs/historical/twirl-and-rsa-key-size.htm#table1 @@ -300,7 +307,7 @@ def create_rsa_signature(private_key, data, scheme="rsassa-pss-sha256"): # explicitly check that 'private_key' is not '', we can/should check for a # value and not compare identities with the 'is' keyword. Up to this point # 'private_key' has variable size and can be an empty string. - if not len(private_key): + if not len(private_key): # pylint: disable=use-implicit-booleaness-not-len raise ValueError("The required private key is unset.") try: @@ -346,8 +353,9 @@ def create_rsa_signature(private_key, data, scheme="rsassa-pss-sha256"): # If the PEM data could not be decrypted, or if its structure could not # be decoded successfully. except ValueError: - raise exceptions.CryptoError( - "The private key" " (in PEM format) could not be deserialized." + raise exceptions.CryptoError( # pylint: disable=raise-missing-from + "The private key" + " (in PEM format) could not be deserialized." # pylint: disable=implicit-str-concat ) # 'TypeError' is raised if a password was given and the private key was @@ -355,8 +363,9 @@ def create_rsa_signature(private_key, data, scheme="rsassa-pss-sha256"): # supplied. Note: A passphrase or password is not used when generating # 'private_key', since it should not be encrypted. except TypeError: - raise exceptions.CryptoError( - "The private key was" " unexpectedly encrypted." + raise exceptions.CryptoError( # pylint: disable=raise-missing-from + "The private key was" + " unexpectedly encrypted." # pylint: disable=implicit-str-concat ) # 'cryptography.exceptions.UnsupportedAlgorithm' is raised if the @@ -364,8 +373,9 @@ def create_rsa_signature(private_key, data, scheme="rsassa-pss-sha256"): # the key is encrypted with a symmetric cipher that is not supported by # the backend. except UnsupportedAlgorithm: # pragma: no cover - raise exceptions.CryptoError( - "The private key is" " encrypted with an unsupported algorithm." + raise exceptions.CryptoError( # pylint: disable=raise-missing-from + "The private key is" + " encrypted with an unsupported algorithm." # pylint: disable=implicit-str-concat ) return signature, scheme @@ -558,8 +568,9 @@ def create_rsa_encrypted_pem(private_key, passphrase): backend=default_backend(), ) except ValueError: - raise exceptions.CryptoError( - "The private key" " (in PEM format) could not be deserialized." + raise exceptions.CryptoError( # pylint: disable=raise-missing-from + "The private key" + " (in PEM format) could not be deserialized." # pylint: disable=implicit-str-concat ) else: @@ -1044,7 +1055,9 @@ def _decrypt(file_contents, password): ) except ValueError: - raise exceptions.CryptoError("Invalid encrypted file.") + raise exceptions.CryptoError( # pylint: disable=raise-missing-from + "Invalid encrypted file." + ) # Ensure we have the expected raw data for the delimited cryptographic data. salt = binascii.unhexlify(salt.encode("utf-8")) @@ -1056,9 +1069,11 @@ def _decrypt(file_contents, password): # specified so that the expected derived key is regenerated correctly. # Discard the old "salt" and "iterations" values, as we only need the old # derived key. - junk_old_salt, junk_old_iterations, symmetric_key = _generate_derived_key( - password, salt, iterations - ) + ( + junk_old_salt, # pylint: disable=unused-variable + junk_old_iterations, # pylint: disable=unused-variable + symmetric_key, + ) = _generate_derived_key(password, salt, iterations) # Verify the hmac to ensure the ciphertext is valid and has not been altered. # See the encryption routine for why we use the encrypt-then-MAC approach. diff --git a/securesystemslib/schema.py b/securesystemslib/schema.py index 171a9afd..d1d1e612 100755 --- a/securesystemslib/schema.py +++ b/securesystemslib/schema.py @@ -60,7 +60,7 @@ class Schema: should implement check_match(). """ - def matches(self, object): + def matches(self, object): # pylint: disable=redefined-builtin """ Return True if 'object' matches this schema, False if it doesn't. @@ -75,7 +75,7 @@ def matches(self, object): else: return True - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin """ Abstract method. Classes that inherit from 'Schema' must @@ -111,7 +111,7 @@ class Any(Schema): def __init__(self): pass - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin pass @@ -143,7 +143,7 @@ def __init__(self, string): self._string = string - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if self._string != object: raise exceptions.FormatError( "Expected " + repr(self._string) + " got " + repr(object) @@ -181,7 +181,7 @@ class AnyString(Schema): def __init__(self): pass - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if not isinstance(object, str): raise exceptions.FormatError( "Expected a string" " but got " + repr(object) @@ -217,7 +217,7 @@ class AnyNonemptyString(AnyString): False """ - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin AnyString.check_match(self, object) if object == "": @@ -255,7 +255,7 @@ class AnyBytes(Schema): def __init__(self): pass - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if not isinstance(object, bytes): raise exceptions.FormatError( "Expected a byte string" " but got " + repr(object) @@ -292,7 +292,7 @@ def __init__(self, length): self._string_length = length - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if not isinstance(object, str): raise exceptions.FormatError( "Expected a string but" " got " + repr(object) @@ -335,7 +335,7 @@ def __init__(self, length): self._bytes_length = length - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if not isinstance(object, bytes): raise exceptions.FormatError( "Expected a byte but" " got " + repr(object) @@ -390,14 +390,15 @@ def __init__(self, alternatives): self._alternatives = alternatives - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin # Simply return as soon as we find a match. # Raise 'exceptions.FormatError' if no matches are found. for alternative in self._alternatives: if alternative.matches(object): return raise exceptions.FormatError( - "Object did not match a" " recognized alternative." + "Object did not match a" + " recognized alternative." # pylint: disable=implicit-str-concat ) @@ -436,7 +437,7 @@ def __init__(self, required_schemas): self._required_schemas = required_schemas[:] - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin for required_schema in self._required_schemas: required_schema.check_match(object) @@ -462,7 +463,7 @@ class Boolean(Schema): def __init__(self): pass - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if not isinstance(object, bool): raise exceptions.FormatError( "Got " + repr(object) + " instead of a boolean." @@ -529,10 +530,10 @@ def __init__( self._max_count = max_count self._list_name = list_name - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if not isinstance(object, (list, tuple)): raise exceptions.FormatError( - "Expected object of type {} but got type {}".format( + "Expected object of type {} but got type {}".format( # pylint: disable=consider-using-f-string self._list_name, type(object).__name__ ) ) @@ -595,8 +596,10 @@ def __init__(self, lo=-2147483648, hi=2147483647): self._lo = lo self._hi = hi - def check_match(self, object): - if isinstance(object, bool) or not isinstance(object, int): + def check_match(self, object): # pylint: disable=redefined-builtin + if isinstance( # pylint: disable=no-else-raise + object, bool + ) or not isinstance(object, int): # We need to check for bool as a special case, since bool # is for historical reasons a subtype of int. raise exceptions.FormatError( @@ -660,7 +663,7 @@ def __init__(self, key_schema, value_schema): self._key_schema = key_schema self._value_schema = value_schema - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if not isinstance(object, dict): raise exceptions.FormatError( "Expected a dict but" " got " + repr(object) @@ -704,7 +707,7 @@ def __init__(self, schema): ) self._schema = schema - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin self._schema.check_match(object) @@ -745,7 +748,7 @@ def __init__(self, object_name="object", **required): """ # Ensure valid arguments. - for key, schema in required.items(): + for key, schema in required.items(): # pylint: disable=unused-variable if not isinstance(schema, Schema): raise exceptions.FormatError( "Expected Schema but" " got " + repr(schema) @@ -754,7 +757,7 @@ def __init__(self, object_name="object", **required): self._object_name = object_name self._required = list(required.items()) - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if not isinstance(object, dict): raise exceptions.FormatError( "Wanted a " + repr(self._object_name) + "." @@ -770,7 +773,7 @@ def check_match(self, object): except KeyError: # If not an Optional schema, raise an exception. if not isinstance(schema, Optional): - raise exceptions.FormatError( + raise exceptions.FormatError( # pylint: disable=raise-missing-from "Missing key " + repr(key) + " in " @@ -882,8 +885,10 @@ def __init__( self._allow_more = allow_more self._struct_name = struct_name - def check_match(self, object): - if not isinstance(object, (list, tuple)): + def check_match(self, object): # pylint: disable=redefined-builtin + if not isinstance( # pylint: disable=no-else-raise + object, (list, tuple) + ): raise exceptions.FormatError( "Expected " + repr(self._struct_name) @@ -975,7 +980,7 @@ def __init__(self, pattern=None, modifiers=0, re_object=None, re_name=None): re_name = "pattern" self._re_name = re_name - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if not isinstance(object, str) or not self._re_object.match(object): raise exceptions.FormatError( repr(object) + " did not match " + repr(self._re_name) diff --git a/securesystemslib/storage.py b/securesystemslib/storage.py index c4139003..9ff1e086 100644 --- a/securesystemslib/storage.py +++ b/securesystemslib/storage.py @@ -202,7 +202,10 @@ def get(self, filepath: str) -> Iterator[BinaryIO]: file_object = open(filepath, "rb") yield file_object except OSError: - raise exceptions.StorageError("Can't open %s" % filepath) + raise exceptions.StorageError( # pylint: disable=raise-missing-from + "Can't open %s" # pylint: disable=consider-using-f-string + % filepath + ) finally: if file_object is not None: file_object.close() @@ -246,7 +249,10 @@ def put( destination_file.flush() os.fsync(destination_file.fileno()) except OSError: - raise exceptions.StorageError("Can't write file %s" % filepath) + raise exceptions.StorageError( # pylint: disable=raise-missing-from + "Can't write file %s" # pylint: disable=consider-using-f-string + % filepath + ) def remove(self, filepath: str) -> None: try: @@ -256,13 +262,19 @@ def remove(self, filepath: str) -> None: PermissionError, OSError, ): # pragma: no cover - raise exceptions.StorageError("Can't remove file %s" % filepath) + raise exceptions.StorageError( # pylint: disable=raise-missing-from + "Can't remove file %s" # pylint: disable=consider-using-f-string + % filepath + ) def getsize(self, filepath: str) -> int: try: return os.path.getsize(filepath) except OSError: - raise exceptions.StorageError("Can't access file %s" % filepath) + raise exceptions.StorageError( # pylint: disable=raise-missing-from + "Can't access file %s" # pylint: disable=consider-using-f-string + % filepath + ) def create_folder(self, filepath: str) -> None: try: @@ -279,11 +291,15 @@ def create_folder(self, filepath: str) -> None: ) else: raise exceptions.StorageError( - "Can't create folder at %s" % filepath + "Can't create folder at %s" # pylint: disable=consider-using-f-string + % filepath ) def list_folder(self, filepath: str) -> List[str]: try: return os.listdir(filepath) except FileNotFoundError: - raise exceptions.StorageError("Can't list folder at %s" % filepath) + raise exceptions.StorageError( # pylint: disable=raise-missing-from + "Can't list folder at %s" # pylint: disable=consider-using-f-string + % filepath + ) diff --git a/securesystemslib/unittest_toolbox.py b/securesystemslib/unittest_toolbox.py index d228d36c..ab1e989d 100755 --- a/securesystemslib/unittest_toolbox.py +++ b/securesystemslib/unittest_toolbox.py @@ -25,7 +25,7 @@ import unittest -class Modified_TestCase(unittest.TestCase): +class Modified_TestCase(unittest.TestCase): # pylint: disable=invalid-name """ Provide additional test-setup methods to make testing @@ -106,7 +106,11 @@ def make_temp_data_file(self, suffix="", directory=None, data="junk data"): """Returns an absolute path of a temp file containing data.""" temp_file_path = self.make_temp_file(suffix=suffix, directory=directory) - temp_file = open(temp_file_path, "wt") + temp_file = ( + open( # pylint: disable=unspecified-encoding,consider-using-with + temp_file_path, "wt" + ) + ) temp_file.write(data) temp_file.close() @@ -116,7 +120,7 @@ def random_path(self, length=7): """Generate a 'random' path consisting of random n-length strings.""" rand_path = "/" + self.random_string(length) - for i in range(2): + for i in range(2): # pylint: disable=unused-variable rand_path = os.path.join(rand_path, self.random_string(length)) return rand_path @@ -126,7 +130,7 @@ def random_string(length=15): """Generate a random string of specified length.""" rand_str = "" - for letter in range(length): + for letter in range(length): # pylint: disable=unused-variable rand_str += random.choice("abcdefABCDEF" + string.digits) return rand_str diff --git a/securesystemslib/util.py b/securesystemslib/util.py index 182c189a..755f13aa 100644 --- a/securesystemslib/util.py +++ b/securesystemslib/util.py @@ -29,7 +29,7 @@ logger = logging.getLogger(__name__) -def get_file_details( +def get_file_details( # pylint: disable=dangerous-default-value filepath: str, hash_algorithms: List[str] = ["sha256"], storage_backend: Optional[StorageBackendInterface] = None, @@ -78,7 +78,7 @@ def get_file_details( return file_length, file_hashes -def get_file_hashes( +def get_file_hashes( # pylint: disable=dangerous-default-value filepath: str, hash_algorithms: List[str] = ["sha256"], storage_backend: Optional[StorageBackendInterface] = None, @@ -348,11 +348,11 @@ def load_json_string(data: Union[str, bytes]) -> Any: except TypeError: message = "Invalid JSON string: " + repr(data) - raise exceptions.Error(message) + raise exceptions.Error(message) # pylint: disable=raise-missing-from except ValueError: message = "Cannot deserialize to a Python object: " + repr(data) - raise exceptions.Error(message) + raise exceptions.Error(message) # pylint: disable=raise-missing-from else: return deserialized_object @@ -407,7 +407,7 @@ def load_json_file( deserialized_object = json.loads(raw_data) except (ValueError, TypeError): - raise exceptions.Error( + raise exceptions.Error( # pylint: disable=raise-missing-from "Cannot deserialize to a" " Python object: " + filepath ) @@ -450,7 +450,9 @@ def digests_are_equal(digest1: str, digest2: str) -> bool: are_equal = True - for element in range(len(digest1)): + for element in range( # pylint: disable=consider-using-enumerate + len(digest1) + ): if digest1[element] != digest2[element]: are_equal = False diff --git a/tests/check_public_interfaces.py b/tests/check_public_interfaces.py index 2b54ce6f..8c6190f7 100644 --- a/tests/check_public_interfaces.py +++ b/tests/check_public_interfaces.py @@ -29,8 +29,8 @@ when explicitly invoked. """ -import inspect -import json +import inspect # pylint: disable=unused-import +import json # pylint: disable=unused-import import os import shutil import sys @@ -38,19 +38,21 @@ import unittest if sys.version_info >= (3, 3): - import unittest.mock as mock + import unittest.mock as mock # pylint: disable=consider-using-from-import else: import mock -import securesystemslib.exceptions -import securesystemslib.gpg.constants -import securesystemslib.gpg.functions -import securesystemslib.gpg.util -import securesystemslib.interface -import securesystemslib.keys +import securesystemslib.exceptions # pylint: disable=wrong-import-position +import securesystemslib.gpg.constants # pylint: disable=wrong-import-position +import securesystemslib.gpg.functions # pylint: disable=wrong-import-position +import securesystemslib.gpg.util # pylint: disable=wrong-import-position +import securesystemslib.interface # pylint: disable=wrong-import-position +import securesystemslib.keys # pylint: disable=wrong-import-position -class TestPublicInterfaces(unittest.TestCase): +class TestPublicInterfaces( + unittest.TestCase +): # pylint: disable=missing-class-docstring @classmethod def setUpClass(cls): cls.temp_dir = tempfile.mkdtemp(dir=os.getcwd()) @@ -64,7 +66,7 @@ def test_interface(self): with self.assertRaises( securesystemslib.exceptions.UnsupportedLibraryError ): - securesystemslib.interface._generate_and_write_rsa_keypair( + securesystemslib.interface._generate_and_write_rsa_keypair( # pylint: disable=protected-access password="pw" ) @@ -97,13 +99,13 @@ def test_interface(self): securesystemslib.exceptions.UnsupportedLibraryError ): path = os.path.join(self.temp_dir, "rsa_key") - with open(path, "a"): + with open(path, "a"): # pylint: disable=unspecified-encoding securesystemslib.interface.import_rsa_privatekey_from_file(path) with self.assertRaises( securesystemslib.exceptions.UnsupportedLibraryError ): - securesystemslib.interface._generate_and_write_ed25519_keypair( + securesystemslib.interface._generate_and_write_ed25519_keypair( # pylint: disable=protected-access password="pw" ) @@ -131,7 +133,7 @@ def test_interface(self): securesystemslib.exceptions.UnsupportedLibraryError ): path = os.path.join(self.temp_dir, "ed25519_priv.json") - with open(path, "a") as f: + with open(path, "a") as f: # pylint: disable=unspecified-encoding f.write("{}") securesystemslib.interface.import_ed25519_privatekey_from_file( path, "pw" @@ -140,7 +142,7 @@ def test_interface(self): with self.assertRaises( securesystemslib.exceptions.UnsupportedLibraryError ): - securesystemslib.interface._generate_and_write_ecdsa_keypair( + securesystemslib.interface._generate_and_write_ecdsa_keypair( # pylint: disable=protected-access password="pw" ) @@ -168,7 +170,7 @@ def test_interface(self): securesystemslib.exceptions.UnsupportedLibraryError ): path = os.path.join(self.temp_dir, "ecddsa.priv") - with open(path, "a") as f: + with open(path, "a") as f: # pylint: disable=unspecified-encoding f.write("{}") securesystemslib.interface.import_ecdsa_privatekey_from_file( path, password="pw" diff --git a/tests/check_public_interfaces_gpg.py b/tests/check_public_interfaces_gpg.py index 032e3cd4..4fc81809 100644 --- a/tests/check_public_interfaces_gpg.py +++ b/tests/check_public_interfaces_gpg.py @@ -37,7 +37,9 @@ from securesystemslib.gpg.util import get_version -class TestPublicInterfacesGPG(unittest.TestCase): +class TestPublicInterfacesGPG( + unittest.TestCase +): # pylint: disable=missing-class-docstring @classmethod def setUpClass(cls): assert ( diff --git a/tests/test_ecdsa_keys.py b/tests/test_ecdsa_keys.py index bb05f049..fc9b90ce 100755 --- a/tests/test_ecdsa_keys.py +++ b/tests/test_ecdsa_keys.py @@ -17,7 +17,7 @@ Test cases for test_ecdsa_keys.py. """ -import os +import os # pylint: disable=unused-import import unittest import securesystemslib.ecdsa_keys @@ -31,14 +31,16 @@ ) -class TestECDSA_keys(unittest.TestCase): +class TestECDSA_keys( + unittest.TestCase +): # pylint: disable=missing-class-docstring,invalid-name def setUp(self): pass def test_generate_public_and_private(self): ( - public, - private, + public, # pylint: disable=redefined-outer-name + private, # pylint: disable=redefined-outer-name ) = securesystemslib.ecdsa_keys.generate_public_and_private() # Check format of 'public' and 'private'. @@ -57,8 +59,8 @@ def test_generate_public_and_private(self): ) def test_create_ecdsa_public_and_private_from_pem(self): - global public - global private + global public # pylint: disable=global-statement + global private # pylint: disable=global-statement # Check format of 'public' and 'private'. self.assertEqual( @@ -91,8 +93,8 @@ def test_create_ecdsa_public_and_private_from_pem(self): ) def test_create_signature(self): - global public - global private + global public # pylint: disable=global-variable-not-assigned + global private # pylint: disable=global-variable-not-assigned data = b"The quick brown fox jumps over the lazy dog" signature, method = securesystemslib.ecdsa_keys.create_signature( public, private, data @@ -136,8 +138,8 @@ def test_create_signature(self): ) def test_verify_signature(self): - global public - global private + global public # pylint: disable=global-variable-not-assigned + global private # pylint: disable=global-variable-not-assigned data = b"The quick brown fox jumps over the lazy dog" scheme = "ecdsa-sha2-nistp256" signature, scheme = securesystemslib.ecdsa_keys.create_signature( @@ -153,7 +155,7 @@ def test_verify_signature(self): # rejected. ( rsa_pem, - junk, + junk, # pylint: disable=unused-variable ) = securesystemslib.rsa_keys.generate_rsa_public_and_private() # Verify that a non-ECDSA key (via the PEM argument) is rejected. diff --git a/tests/test_ed25519_keys.py b/tests/test_ed25519_keys.py index 7f1ae66d..6b5134b8 100755 --- a/tests/test_ed25519_keys.py +++ b/tests/test_ed25519_keys.py @@ -30,7 +30,9 @@ ) -class TestEd25519_keys(unittest.TestCase): +class TestEd25519_keys( + unittest.TestCase +): # pylint: disable=missing-class-docstring,invalid-name def setUp(self): pass @@ -46,8 +48,8 @@ def test_generate_public_and_private(self): ) def test_create_signature(self): - global public - global private + global public # pylint: disable=global-variable-not-assigned + global private # pylint: disable=global-variable-not-assigned data = b"The quick brown fox jumps over the lazy dog" scheme = "ed25519" signature, scheme = securesystemslib.ed25519_keys.create_signature( @@ -95,8 +97,8 @@ def test_create_signature(self): ) def test_verify_signature(self): - global public - global private + global public # pylint: disable=global-variable-not-assigned + global private # pylint: disable=global-variable-not-assigned data = b"The quick brown fox jumps over the lazy dog" scheme = "ed25519" signature, scheme = securesystemslib.ed25519_keys.create_signature( diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 18b640a6..cb227219 100755 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -25,7 +25,9 @@ logger = logging.getLogger(__name__) -class TestExceptions(unittest.TestCase): +class TestExceptions( + unittest.TestCase +): # pylint: disable=missing-class-docstring def setUp(self): pass diff --git a/tests/test_formats.py b/tests/test_formats.py index 1fe445a8..afa4d33c 100755 --- a/tests/test_formats.py +++ b/tests/test_formats.py @@ -24,7 +24,7 @@ import securesystemslib.schema -class TestFormats(unittest.TestCase): +class TestFormats(unittest.TestCase): # pylint: disable=missing-class-docstring def setUp(self): pass @@ -220,7 +220,10 @@ def test_schemas(self): # Iterate 'valid_schemas', ensuring each 'valid_schema' correctly matches # its respective 'schema_type'. - for schema_name, (schema_type, valid_schema) in valid_schemas.items(): + for schema_name, ( # pylint: disable=unused-variable + schema_type, + valid_schema, + ) in valid_schemas.items(): if not schema_type.matches(valid_schema): print("bad schema: " + repr(valid_schema)) @@ -238,7 +241,9 @@ def test_schemas(self): def test_unix_timestamp_to_datetime(self): # Test conditions for valid arguments. - UNIX_TIMESTAMP_SCHEMA = securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA + UNIX_TIMESTAMP_SCHEMA = ( # pylint: disable=invalid-name,unused-variable + securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA + ) self.assertTrue( datetime.datetime, securesystemslib.formats.unix_timestamp_to_datetime(499137720), @@ -362,7 +367,7 @@ def test_encode_canonical(self): encode = securesystemslib.formats.encode_canonical result = [] output = result.append - bad_output = 123 + bad_output = 123 # pylint: disable=unused-variable self.assertEqual('""', encode("")) self.assertEqual("[1,2,3]", encode([1, 2, 3])) diff --git a/tests/test_gpg.py b/tests/test_gpg.py index fb56e675..5431de73 100644 --- a/tests/test_gpg.py +++ b/tests/test_gpg.py @@ -32,12 +32,13 @@ else: from mock import patch # pylint: disable=import-error +# pylint: disable=wrong-import-position from collections import OrderedDict from copy import deepcopy -import cryptography.hazmat.backends as backends +import cryptography.hazmat.backends as backends # pylint: disable=consider-using-from-import import cryptography.hazmat.primitives.hashes as hashing -import cryptography.hazmat.primitives.serialization as serialization +import cryptography.hazmat.primitives.serialization as serialization # pylint: disable=consider-using-from-import from securesystemslib import exceptions, process from securesystemslib.formats import ANY_PUBKEY_DICT_SCHEMA, GPG_PUBKEY_SCHEMA @@ -61,8 +62,12 @@ have_gpg, ) from securesystemslib.gpg.dsa import create_pubkey as dsa_create_pubkey + +# pylint: disable=unused-import from securesystemslib.gpg.eddsa import ED25519_SIG_LENGTH from securesystemslib.gpg.eddsa import create_pubkey as eddsa_create_pubkey + +# pylint: enable=unused-import from securesystemslib.gpg.exceptions import ( CommandError, KeyExpirationError, @@ -87,12 +92,16 @@ parse_subpacket_header, ) +# pylint: enable=wrong-import-position + class GPGTestUtils: """GPG Test utility class""" @staticmethod - def ignore_not_found_error(function, path, exc_info): + def ignore_not_found_error( + function, path, exc_info + ): # pylint: disable=unused-argument,unused-argument """Callback that ignores FileNotFoundError""" _, error, _ = exc_info if not isinstance(error, FileNotFoundError): @@ -223,11 +232,15 @@ class TestCommon(unittest.TestCase): """Test common functions of the securesystemslib.gpg module.""" @classmethod - def setUpClass(self): + def setUpClass(self): # pylint: disable=bad-classmethod-argument gpg_keyring_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "gpg_keyrings", "rsa" ) - homearg = "--homedir {}".format(gpg_keyring_path).replace("\\", "/") + homearg = ( + "--homedir {}".format( # pylint: disable=consider-using-f-string + gpg_keyring_path + ).replace("\\", "/") + ) # Load test raw public key bundle from rsa keyring, used to construct # erroneous gpg data in tests below. @@ -402,7 +415,9 @@ def test_assign_certified_key_info_errors(self): msg = str(mock_log.info.call_args[0][0]) self.assertTrue( expected_msg in msg, - "'{}' not in '{}'".format(expected_msg, msg), + "'{}' not in '{}'".format( # pylint: disable=consider-using-f-string + expected_msg, msg + ), ) def test_assign_certified_key_info_expiration(self): @@ -513,7 +528,9 @@ def test_get_verified_subkeys_errors(self): msg = str(mock_log.info.call_args[0][0]) self.assertTrue( expected_msg in msg, - "'{}' not in '{}'".format(expected_msg, msg), + "'{}' not in '{}'".format( # pylint: disable=consider-using-f-string + expected_msg, msg + ), ) def test_get_verified_subkeys(self): @@ -530,9 +547,9 @@ def test_get_verified_subkeys(self): # Test subkey without validity period, i.e. it does not expire self.assertTrue( - subkeys["70cfabf1e2f1dc60ac5c7bca10cd20d3d5bcb6ef"].get( - "validity_period" - ) + subkeys[ # pylint: disable=singleton-comparison + "70cfabf1e2f1dc60ac5c7bca10cd20d3d5bcb6ef" + ].get("validity_period") == None ) @@ -574,7 +591,7 @@ def test_parse_signature_packet_errors(self): parse_signature_packet(data) self.assertTrue( expected_error_str in str(ctx.exception), - "'{}' not in '{}'".format( + "'{}' not in '{}'".format( # pylint: disable=consider-using-f-string expected_error_str, str(ctx.exception) ), ) @@ -591,10 +608,10 @@ class TestGPGRSA(unittest.TestCase): unsupported_subkey_keyid = "611A9B648E16F54E8A7FAD5DA51E8CDF3B06524F" expired_key_keyid = "E8AC80C924116DABB51D4B987CB07D6D2C199C7C" - keyid_768C43 = "7B3ABB26B97B655AB9296BD15B0BD02E1C768C43" + keyid_768C43 = "7B3ABB26B97B655AB9296BD15B0BD02E1C768C43" # pylint: disable=invalid-name @classmethod - def setUpClass(self): + def setUpClass(self): # pylint: disable=bad-classmethod-argument # Create directory to run the tests without having everything blow up self.working_dir = os.getcwd() @@ -609,7 +626,7 @@ def setUpClass(self): os.chdir(self.test_dir) @classmethod - def tearDownClass(self): + def tearDownClass(self): # pylint: disable=bad-classmethod-argument """Change back to initial working dir and remove temp test directory.""" os.chdir(self.working_dir) shutil.rmtree( @@ -634,7 +651,11 @@ def test_export_pubkey(self): # load the equivalent ssh key, and make sure that we get the same RSA key # parameters - ssh_key_basename = "{}.ssh".format(self.default_keyid) + ssh_key_basename = ( + "{}.ssh".format( # pylint: disable=consider-using-f-string + self.default_keyid + ) + ) ssh_key_path = os.path.join(self.gnupg_home, ssh_key_basename) with open(ssh_key_path, "rb") as fp: keydata = fp.read() @@ -731,7 +752,9 @@ def test_create_signature_with_expired_key(self): expected = "returned non-zero exit status '2'" self.assertTrue( expected in str(ctx.exception), - "{} not in {}".format(expected, ctx.exception), + "{} not in {}".format( # pylint: disable=consider-using-f-string + expected, ctx.exception + ), ) def test_verify_signature_with_expired_key(self): @@ -754,7 +777,10 @@ def test_verify_signature_with_expired_key(self): ) self.assertTrue( expected == str(ctx.exception), - "\nexpected: {}" "\ngot: {}".format(expected, ctx.exception), + "\nexpected: {}" # pylint: disable=consider-using-f-string + "\ngot: {}".format( # pylint: disable=consider-using-f-string + expected, ctx.exception + ), ) @@ -766,7 +792,7 @@ class TestGPGDSA(unittest.TestCase): default_keyid = "C242A830DAAF1C2BEF604A9EF033A3A3E267B3B1" @classmethod - def setUpClass(self): + def setUpClass(self): # pylint: disable=bad-classmethod-argument # Create directory to run the tests without having everything blow up self.working_dir = os.getcwd() self.test_dir = os.path.realpath(tempfile.mkdtemp()) @@ -781,7 +807,7 @@ def setUpClass(self): os.chdir(self.test_dir) @classmethod - def tearDownClass(self): + def tearDownClass(self): # pylint: disable=bad-classmethod-argument """Change back to initial working dir and remove temp test directory.""" os.chdir(self.working_dir) shutil.rmtree( @@ -800,7 +826,11 @@ def test_export_pubkey(self): our_exported_key = dsa_create_pubkey(key_data) # load same key, pre-exported with 3rd-party tooling - pem_key_basename = "{}.pem".format(self.default_keyid) + pem_key_basename = ( + "{}.pem".format( # pylint: disable=consider-using-f-string + self.default_keyid + ) + ) pem_key_path = os.path.join(self.gnupg_home, pem_key_basename) with open(pem_key_path, "rb") as fp: keydata = fp.read() @@ -861,7 +891,7 @@ class TestGPGEdDSA(unittest.TestCase): default_keyid = "4E630F84838BF6F7447B830B22692F5FEA9E2DD2" @classmethod - def setUpClass(self): + def setUpClass(self): # pylint: disable=bad-classmethod-argument # Create directory to run the tests without having everything blow up self.working_dir = os.getcwd() self.test_dir = os.path.realpath(tempfile.mkdtemp()) @@ -876,7 +906,7 @@ def setUpClass(self): os.chdir(self.test_dir) @classmethod - def tearDownClass(self): + def tearDownClass(self): # pylint: disable=bad-classmethod-argument """Change back to initial working dir and remove temp test directory.""" os.chdir(self.working_dir) shutil.rmtree( diff --git a/tests/test_hash.py b/tests/test_hash.py index b5f73f12..f13ce3bb 100755 --- a/tests/test_hash.py +++ b/tests/test_hash.py @@ -21,7 +21,7 @@ import io import logging import os -import sys +import sys # pylint: disable=unused-import import tempfile import unittest @@ -31,11 +31,14 @@ logger = logging.getLogger(__name__) -if not "hashlib" in securesystemslib.hash.SUPPORTED_LIBRARIES: +if ( + not "hashlib" # pylint: disable=unneeded-not + in securesystemslib.hash.SUPPORTED_LIBRARIES +): logger.warning("Not testing hashlib: could not be imported.") -class TestHash(unittest.TestCase): +class TestHash(unittest.TestCase): # pylint: disable=missing-class-docstring @staticmethod def _is_supported_combination(library, algorithm): blake_algos = ["blake2b", "blake2b-256", "blake2s"] @@ -46,7 +49,9 @@ def _is_supported_combination(library, algorithm): return False return True - def _run_with_all_algos_and_libs(self, test_func): + def _run_with_all_algos_and_libs( + self, test_func + ): # pylint: disable=missing-function-docstring algorithms = [ "md5", "sha1", @@ -73,7 +78,9 @@ def _run_with_all_hash_libraries(self, test_func, algorithm): algorithm, ) - def _do_algorithm_update(self, library, algorithm): + def _do_algorithm_update( + self, library, algorithm + ): # pylint: disable=missing-function-docstring expected = { "blake2b": [ "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce", @@ -185,7 +192,9 @@ def _do_unsupported_algorithm(self, library, algorithm): def test_digest_size(self): self._run_with_all_algos_and_libs(self._do_digest_size) - def _do_digest_size(self, library, algorithm): + def _do_digest_size( + self, library, algorithm + ): # pylint: disable=missing-function-docstring digest_sizes = { "md5": 16, "sha1": 20, @@ -205,7 +214,9 @@ def _do_digest_size(self, library, algorithm): def test_update_filename(self): self._run_with_all_algos_and_libs(self._do_update_filename) - def _do_update_filename(self, library, algorithm): + def _do_update_filename( + self, library, algorithm + ): # pylint: disable=missing-function-docstring data = "abcdefgh" * 4096 fd, filename = tempfile.mkstemp() try: @@ -228,7 +239,9 @@ def _do_update_filename(self, library, algorithm): def test_update_filename_normalize(self): self._run_with_all_algos_and_libs(self._do_update_filename_normalize) - def _do_update_filename_normalize(self, library, algorithm): + def _do_update_filename_normalize( + self, library, algorithm + ): # pylint: disable=missing-function-docstring data = b"ab\r\nd\nf\r" * 4096 normalized_data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n") fd, filename = tempfile.mkstemp() @@ -252,7 +265,9 @@ def _do_update_filename_normalize(self, library, algorithm): def test_update_file_obj(self): self._run_with_all_algos_and_libs(self._do_update_file_obj) - def _do_update_file_obj(self, library, algorithm): + def _do_update_file_obj( + self, library, algorithm + ): # pylint: disable=missing-function-docstring data = "abcdefgh" * 4096 file_obj = io.StringIO() file_obj.write(data) @@ -285,7 +300,9 @@ def _do_get_digest_from_rsa_valid_schemes(self, library, algorithm): expected_digest_cls, ) - def _do_get_digest_from_rsa_non_valid_schemes(self, library, algorithm): + def _do_get_digest_from_rsa_non_valid_schemes( + self, library, algorithm + ): # pylint: disable=unused-argument self.assertRaises( securesystemslib.exceptions.FormatError, securesystemslib.hash.digest_from_rsa_scheme, diff --git a/tests/test_interface.py b/tests/test_interface.py index 90115d06..260bdeec 100755 --- a/tests/test_interface.py +++ b/tests/test_interface.py @@ -17,14 +17,14 @@ Unit test for 'interface.py'. """ -import datetime -import json +import datetime # pylint: disable=unused-import +import json # pylint: disable=unused-import import os import shutil import stat import sys import tempfile -import time +import time # pylint: disable=unused-import import unittest from cryptography.hazmat.backends import default_backend @@ -32,21 +32,29 @@ # Use external backport 'mock' on versions under 3.3 if sys.version_info >= (3, 3): - import unittest.mock as mock + import unittest.mock as mock # pylint: disable=consider-using-from-import else: import mock -from securesystemslib import KEY_TYPE_ECDSA, KEY_TYPE_ED25519, KEY_TYPE_RSA -from securesystemslib.exceptions import CryptoError, Error, FormatError -from securesystemslib.formats import ( +from securesystemslib import ( # pylint: disable=wrong-import-position + KEY_TYPE_ECDSA, + KEY_TYPE_ED25519, + KEY_TYPE_RSA, +) +from securesystemslib.exceptions import ( # pylint: disable=wrong-import-position + CryptoError, + Error, + FormatError, +) +from securesystemslib.formats import ( # pylint: disable=wrong-import-position ANY_PUBKEY_DICT_SCHEMA, ECDSAKEY_SCHEMA, ED25519KEY_SCHEMA, PUBLIC_KEY_SCHEMA, RSAKEY_SCHEMA, ) -from securesystemslib.interface import ( +from securesystemslib.interface import ( # pylint: disable=wrong-import-position _generate_and_write_ecdsa_keypair, _generate_and_write_ed25519_keypair, _generate_and_write_rsa_keypair, @@ -70,7 +78,9 @@ ) -class TestInterfaceFunctions(unittest.TestCase): +class TestInterfaceFunctions( + unittest.TestCase +): # pylint: disable=missing-class-docstring @classmethod def setUpClass(cls): cls.test_data_dir = os.path.join( @@ -96,7 +106,7 @@ def tearDown(self): os.chdir(self.orig_cwd) shutil.rmtree(self.tmp_dir) - def test_rsa(self): + def test_rsa(self): # pylint: disable=too-many-locals,too-many-statements """Test RSA key _generation and import interface functions.""" # TEST: Generate default keys and import @@ -199,14 +209,17 @@ def test_rsa(self): ): with self.assertRaises( - ValueError, msg="(row {})".format(idx) + ValueError, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), ) as ctx: _generate_and_write_rsa_keypair(**kwargs) self.assertEqual( err_msg, str(ctx.exception), - "expected: '{}' got: '{}' (row {})".format( + "expected: '{}' got: '{}' (row {})".format( # pylint: disable=consider-using-f-string err_msg, ctx.exception, idx ), ) @@ -221,7 +234,12 @@ def test_rsa(self): {"prompt": "not-a-bool"}, ] ): - with self.assertRaises(FormatError, msg="(row {})".format(idx)): + with self.assertRaises( + FormatError, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ): _generate_and_write_rsa_keypair(**kwargs) # TEST: Import errors @@ -233,7 +251,9 @@ def test_rsa(self): self.assertTrue( err_msg in str(ctx.exception), - "expected: '{}' got: '{}'".format(err_msg, ctx.exception), + "expected: '{}' got: '{}'".format( # pylint: disable=consider-using-f-string + err_msg, ctx.exception + ), ) # Error on private key import... @@ -284,12 +304,17 @@ def test_rsa(self): ] ): - with self.assertRaises(err, msg="(row {})".format(idx)) as ctx: + with self.assertRaises( + err, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ) as ctx: import_rsa_privatekey_from_file(*args, **kwargs) self.assertTrue( err_msg in str(ctx.exception), - "expected: '{}' got: '{}' (row {})".format( + "expected: '{}' got: '{}' (row {})".format( # pylint: disable=consider-using-f-string err_msg, ctx.exception, idx ), ) @@ -303,7 +328,9 @@ def test_rsa(self): self.assertTrue( err_msg in str(ctx.exception), - "expected: '{}' got: '{}'".format(err_msg, ctx.exception), + "expected: '{}' got: '{}'".format( # pylint: disable=consider-using-f-string + err_msg, ctx.exception + ), ) # Error on bad argument format @@ -314,9 +341,19 @@ def test_rsa(self): ([fn_default], {"scheme": "bad scheme"}), # bad scheme ] ): - with self.assertRaises(FormatError, msg="(row {})".format(idx)): + with self.assertRaises( + FormatError, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ): import_rsa_publickey_from_file(*args, **kwargs) - with self.assertRaises(FormatError, msg="(row {})".format(idx)): + with self.assertRaises( + FormatError, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ): import_rsa_privatekey_from_file(*args, **kwargs) # bad password @@ -327,7 +364,9 @@ def test_rsa(self): with self.assertRaises(FormatError): import_rsa_privatekey_from_file(fn_default, prompt="not-a-bool") - def test_ed25519(self): + def test_ed25519( + self, + ): # pylint: disable=too-many-locals,too-many-statements """Test ed25519 key _generation and import interface functions.""" # TEST: Generate default keys and import @@ -428,14 +467,17 @@ def test_ed25519(self): ): with self.assertRaises( - ValueError, msg="(row {})".format(idx) + ValueError, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), ) as ctx: _generate_and_write_ed25519_keypair(**kwargs) self.assertEqual( err_msg, str(ctx.exception), - "expected: '{}' got: '{}' (row {})".format( + "expected: '{}' got: '{}' (row {})".format( # pylint: disable=consider-using-f-string err_msg, ctx.exception, idx ), ) @@ -448,7 +490,12 @@ def test_ed25519(self): {"prompt": "not-a-bool"}, ] ): - with self.assertRaises(FormatError, msg="(row {})".format(idx)): + with self.assertRaises( + FormatError, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ): _generate_and_write_ed25519_keypair(**kwargs) # TEST: Import errors @@ -463,12 +510,17 @@ def test_ed25519(self): (self.path_ecdsa + ".pub", "Invalid key type loaded"), ] ): - with self.assertRaises(Error, msg="(row {})".format(idx)) as ctx: + with self.assertRaises( + Error, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ) as ctx: import_ed25519_publickey_from_file(fn) self.assertTrue( err_msg in str(ctx.exception), - "expected: '{}' got: '{}' (row {})".format( + "expected: '{}' got: '{}' (row {})".format( # pylint: disable=consider-using-f-string err_msg, ctx.exception, idx ), ) @@ -523,12 +575,17 @@ def test_ed25519(self): ] ): - with self.assertRaises(err, msg="(row {})".format(idx)) as ctx: + with self.assertRaises( + err, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ) as ctx: import_ed25519_privatekey_from_file(*args, **kwargs) self.assertTrue( err_msg in str(ctx.exception), - "expected: '{}' got: '{}' (row {})".format( + "expected: '{}' got: '{}' (row {})".format( # pylint: disable=consider-using-f-string err_msg, ctx.exception, idx ), ) @@ -545,7 +602,9 @@ def test_ed25519(self): self.assertTrue( err_msg in str(ctx.exception), - "expected: '{}' got: '{}'".format(err_msg, ctx.exception), + "expected: '{}' got: '{}'".format( # pylint: disable=consider-using-f-string + err_msg, ctx.exception + ), ) # Error on bad path format @@ -562,7 +621,7 @@ def test_ed25519(self): with self.assertRaises(FormatError): import_ed25519_privatekey_from_file(fn_default, prompt="not-a-bool") - def test_ecdsa(self): + def test_ecdsa(self): # pylint: disable=too-many-locals,too-many-statements """Test ecdsa key _generation and import interface functions.""" # TEST: Generate default keys and import # Assert location and format @@ -651,14 +710,17 @@ def test_ecdsa(self): ): with self.assertRaises( - ValueError, msg="(row {})".format(idx) + ValueError, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), ) as ctx: _generate_and_write_ecdsa_keypair(**kwargs) self.assertEqual( err_msg, str(ctx.exception), - "expected: '{}' got: '{}' (row {})".format( + "expected: '{}' got: '{}' (row {})".format( # pylint: disable=consider-using-f-string err_msg, ctx.exception, idx ), ) @@ -671,7 +733,12 @@ def test_ecdsa(self): {"prompt": "not-a-bool"}, ] ): - with self.assertRaises(FormatError, msg="(row {})".format(idx)): + with self.assertRaises( + FormatError, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ): _generate_and_write_ecdsa_keypair(**kwargs) # TEST: Import errors @@ -685,12 +752,17 @@ def test_ecdsa(self): (self.path_no_key, "Missing key"), ] ): - with self.assertRaises(Error, msg="(row {})".format(idx)) as ctx: + with self.assertRaises( + Error, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ) as ctx: import_ecdsa_publickey_from_file(fn) self.assertTrue( err_msg in str(ctx.exception), - "expected: '{}' got: '{}' (row {})".format( + "expected: '{}' got: '{}' (row {})".format( # pylint: disable=consider-using-f-string err_msg, ctx.exception, idx ), ) @@ -743,12 +815,17 @@ def test_ecdsa(self): ] ): - with self.assertRaises(err, msg="(row {})".format(idx)) as ctx: + with self.assertRaises( + err, + msg="(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ) as ctx: import_ecdsa_privatekey_from_file(*args, **kwargs) self.assertTrue( err_msg in str(ctx.exception), - "expected: '{}' got: '{}' (row {})".format( + "expected: '{}' got: '{}' (row {})".format( # pylint: disable=consider-using-f-string err_msg, ctx.exception, idx ), ) @@ -762,7 +839,9 @@ def test_ecdsa(self): self.assertTrue( err_msg in str(ctx.exception), - "expected: '{}' got: '{}'".format(err_msg, ctx.exception), + "expected: '{}' got: '{}'".format( # pylint: disable=consider-using-f-string + err_msg, ctx.exception + ), ) # Error on bad path format @@ -813,7 +892,11 @@ def test_generate_keypair_wrappers(self): ] ): - assert_msg = "(row {})".format(idx) + assert_msg = ( + "(row {})".format( # pylint: disable=consider-using-f-string + idx + ) + ) # Test generate_and_write_*_keypair creates an encrypted private key fn_encrypted = gen(key_pw) priv = import_priv(fn_encrypted, key_pw) @@ -923,7 +1006,12 @@ def test_import_privatekey_from_file(self): key = import_privatekey_from_file( path, key_type=key_type, password=pw ) - self.assertTrue(key_schema.matches(key), "(row {})".format(idx)) + self.assertTrue( + key_schema.matches(key), + "(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ) # ... entered password on mock-prompt with mock.patch( @@ -932,7 +1020,12 @@ def test_import_privatekey_from_file(self): key = import_privatekey_from_file( path, key_type=key_type, prompt=True ) - self.assertTrue(key_schema.matches(key), "(row {})".format(idx)) + self.assertTrue( + key_schema.matches(key), + "(row {})".format( # pylint: disable=consider-using-f-string + idx + ), + ) # Error on wrong key for default key type with self.assertRaises(Error): diff --git a/tests/test_keys.py b/tests/test_keys.py index 530f6f37..f162040f 100755 --- a/tests/test_keys.py +++ b/tests/test_keys.py @@ -34,7 +34,7 @@ DATA = securesystemslib.formats.encode_canonical(DATA_STR).encode("utf-8") -class TestKeys(unittest.TestCase): +class TestKeys(unittest.TestCase): # pylint: disable=missing-class-docstring @classmethod def setUpClass(cls): cls.rsakey_dict = KEYS.generate_rsa_key() @@ -42,7 +42,7 @@ def setUpClass(cls): cls.ecdsakey_dict = KEYS.generate_ecdsa_key() def test_generate_rsa_key(self): - _rsakey_dict = KEYS.generate_rsa_key() + _rsakey_dict = KEYS.generate_rsa_key() # pylint: disable=invalid-name # Check if the format of the object returned by generate() corresponds # to RSAKEY_SCHEMA format. @@ -79,7 +79,9 @@ def test_generate_rsa_key(self): ) def test_generate_ecdsa_key(self): - _ecdsakey_dict = KEYS.generate_ecdsa_key() + _ecdsakey_dict = ( # pylint: disable=invalid-name + KEYS.generate_ecdsa_key() + ) # Check if the format of the object returned by generate_ecdsa_key() # corresponds to ECDSAKEY_SCHEMA format. @@ -208,9 +210,10 @@ def test_format_metadata_to_key(self): del test_rsakey_dict["keyid"] # Call format_metadata_to_key by using the default value for keyid_hash_algorithms - rsakey_dict_from_meta_default, junk = KEYS.format_metadata_to_key( - test_rsakey_dict - ) + ( + rsakey_dict_from_meta_default, + junk, # pylint: disable=unused-variable + ) = KEYS.format_metadata_to_key(test_rsakey_dict) # Check if the format of the object returned by calling this function with # default hash algorithms e.g. securesystemslib.settings.HASH_ALGORITHMS corresponds @@ -291,7 +294,9 @@ def test_helper_get_keyid(self): FORMAT_ERROR_MSG, ) - keyid = KEYS._get_keyid(keytype, scheme, keyvalue) + keyid = KEYS._get_keyid( # pylint: disable=protected-access + keytype, scheme, keyvalue + ) # Check format of 'keyid' - the output of '_get_keyid()' function. self.assertEqual( @@ -368,7 +373,7 @@ def test_create_signature(self): self.assertRaises(TypeError, KEYS.create_signature) self.ecdsakey_dict["keyval"]["private"] = private - def test_verify_signature(self): + def test_verify_signature(self): # pylint: disable=too-many-statements # Creating a signature of 'DATA' to be verified. rsa_signature = KEYS.create_signature(self.rsakey_dict, DATA) ed25519_signature = KEYS.create_signature(self.ed25519key_dict, DATA) @@ -425,8 +430,10 @@ def test_verify_signature(self): # 'rsa_signature'. Function should return 'False'. # Modifying 'DATA'. - _DATA_STR = "1111" + DATA_STR + "1111" - _DATA = securesystemslib.formats.encode_canonical(_DATA_STR).encode( + _DATA_STR = "1111" + DATA_STR + "1111" # pylint: disable=invalid-name + _DATA = securesystemslib.formats.encode_canonical( # pylint: disable=invalid-name + _DATA_STR + ).encode( "utf-8" ) @@ -476,8 +483,12 @@ def test_verify_signature(self): # Verify that the pure python 'ed25519' base case (triggered if 'pynacl' # is unavailable) is executed in securesystemslib.keys.verify_signature(). - KEYS._ED25519_CRYPTO_LIBRARY = "invalid" - KEYS._available_crypto_libraries = ["invalid"] + KEYS._ED25519_CRYPTO_LIBRARY = ( # pylint: disable=protected-access + "invalid" + ) + KEYS._available_crypto_libraries = [ # pylint: disable=protected-access + "invalid" + ] verified = KEYS.verify_signature( self.ed25519key_dict, ed25519_signature, DATA ) @@ -537,7 +548,9 @@ def test_import_rsakey_from_private_pem(self): # Try to import an rsakey from a valid PEM. private_pem = self.rsakey_dict["keyval"]["private"] - private_rsakey = KEYS.import_rsakey_from_private_pem(private_pem) + private_rsakey = KEYS.import_rsakey_from_private_pem( # pylint: disable=unused-variable + private_pem + ) # Test for invalid arguments. self.assertRaises( @@ -663,14 +676,16 @@ def test_import_rsakey_from_pem(self): def test_import_ecdsakey_from_private_pem(self): # Try to import an ecdsakey from a valid PEM. private_pem = self.ecdsakey_dict["keyval"]["private"] - ecdsakey = KEYS.import_ecdsakey_from_private_pem(private_pem) + ecdsakey = KEYS.import_ecdsakey_from_private_pem( # pylint: disable=unused-variable + private_pem + ) # Test for an encrypted PEM. scheme = "ecdsa-sha2-nistp256" encrypted_pem = securesystemslib.ecdsa_keys.create_ecdsa_encrypted_pem( private_pem, "password" ) - private_ecdsakey = KEYS.import_ecdsakey_from_private_pem( + private_ecdsakey = KEYS.import_ecdsakey_from_private_pem( # pylint: disable=unused-variable encrypted_pem.decode("utf-8"), scheme, "password" ) diff --git a/tests/test_process.py b/tests/test_process.py index fbadc750..61e75451 100644 --- a/tests/test_process.py +++ b/tests/test_process.py @@ -27,7 +27,7 @@ import securesystemslib.settings -class Test_Process(unittest.TestCase): +class Test_Process(unittest.TestCase): # pylint: disable=invalid-name """Test subprocess interface.""" def test_run_input_vs_stdin(self): @@ -38,7 +38,11 @@ def test_run_input_vs_stdin(self): os.write(fd, b"use stdin kwarg") os.close(fd) - stdin_file = open(path) + stdin_file = ( + open( # pylint: disable=unspecified-encoding,consider-using-with + path + ) + ) cmd = ( sys.executable + " -c \"import sys; assert(sys.stdin.read() == '{}')\"" @@ -73,11 +77,13 @@ def test_run_duplicate_streams(self): # Create and open fake targets for standard streams stdout_fd, stdout_fn = tempfile.mkstemp() stderr_fd, stderr_fn = tempfile.mkstemp() - with io.open(stdout_fn, "r") as fake_stdout_reader, os.fdopen( + with io.open( # pylint: disable=unspecified-encoding + stdout_fn, "r" + ) as fake_stdout_reader, os.fdopen( # pylint: disable=unspecified-encoding stdout_fd, "w" - ) as fake_stdout_writer, io.open( + ) as fake_stdout_writer, io.open( # pylint: disable=unspecified-encoding stderr_fn, "r" - ) as fake_stderr_reader, os.fdopen( + ) as fake_stderr_reader, os.fdopen( # pylint: disable=unspecified-encoding stderr_fd, "w" ) as fake_stderr_writer: @@ -140,14 +146,16 @@ def test__default_timeout(self): # Backup timeout and check that it is what's returned by _default_timeout() timeout_old = securesystemslib.settings.SUBPROCESS_TIMEOUT self.assertEqual( - securesystemslib.process._default_timeout(), timeout_old + securesystemslib.process._default_timeout(), # pylint: disable=protected-access + timeout_old, ) # Modify timeout and check that _default_timeout() returns the same value timeout_new = timeout_old + 1 securesystemslib.settings.SUBPROCESS_TIMEOUT = timeout_new self.assertEqual( - securesystemslib.process._default_timeout(), timeout_new + securesystemslib.process._default_timeout(), # pylint: disable=protected-access + timeout_new, ) # Restore original timeout diff --git a/tests/test_rsa_keys.py b/tests/test_rsa_keys.py index 0571bb5a..1ff26619 100755 --- a/tests/test_rsa_keys.py +++ b/tests/test_rsa_keys.py @@ -38,7 +38,9 @@ ) -class TestRSA_keys(unittest.TestCase): +class TestRSA_keys( + unittest.TestCase +): # pylint: disable=missing-class-docstring,invalid-name def setUp(self): pass @@ -71,8 +73,8 @@ def test_generate_rsa_public_and_private(self): ) def test_create_rsa_signature(self): - global private_rsa - global public_rsa + global private_rsa # pylint: disable=global-variable-not-assigned + global public_rsa # pylint: disable=global-variable-not-assigned data = "The quick brown fox jumps over the lazy dog".encode("utf-8") for rsa_scheme in securesystemslib.keys.RSA_SIGNATURE_SCHEMES: @@ -149,8 +151,8 @@ def test_create_rsa_signature(self): ) def test_verify_rsa_signature(self): - global public_rsa - global private_rsa + global public_rsa # pylint: disable=global-variable-not-assigned + global private_rsa # pylint: disable=global-variable-not-assigned data = "The quick brown fox jumps over the lazy dog".encode("utf-8") for rsa_scheme in securesystemslib.keys.RSA_SIGNATURE_SCHEMES: @@ -287,8 +289,8 @@ def test_verify_rsa_pss_different_salt_lengths(self): self.assertTrue(verified) def test_create_rsa_encrypted_pem(self): - global public_rsa - global private_rsa + global public_rsa # pylint: disable=global-variable-not-assigned + global private_rsa # pylint: disable=global-variable-not-assigned encrypted_pem = securesystemslib.rsa_keys.create_rsa_encrypted_pem( private_rsa, "password" @@ -328,8 +330,8 @@ def test_create_rsa_encrypted_pem(self): ) def test_create_rsa_public_and_private_from_pem(self): - global public_rsa - global private_rsa + global public_rsa # pylint: disable=global-variable-not-assigned + global private_rsa # pylint: disable=global-variable-not-assigned ( public, @@ -348,8 +350,8 @@ def test_create_rsa_public_and_private_from_pem(self): ) def test_encrypt_key(self): - global public_rsa - global private_rsa + global public_rsa # pylint: disable=global-variable-not-assigned + global private_rsa # pylint: disable=global-variable-not-assigned key_object = { "keytype": "rsa", @@ -376,8 +378,8 @@ def test_encrypt_key(self): def test_decrypt_key(self): # Test for valid arguments. - global public_rsa - global private_rsa + global public_rsa # pylint: disable=global-variable-not-assigned + global private_rsa # pylint: disable=global-variable-not-assigned passphrase = "pw" rsa_key = { @@ -391,7 +393,7 @@ def test_decrypt_key(self): rsa_key, passphrase ) - decrypted_rsa_key = securesystemslib.rsa_keys.decrypt_key( + decrypted_rsa_key = securesystemslib.rsa_keys.decrypt_key( # pylint: disable=unused-variable encrypted_rsa_key, passphrase ) @@ -404,7 +406,9 @@ def test_decrypt_key(self): ) # Test for invalid encrypted content (i.e., invalid hmac and ciphertext.) - encryption_delimiter = securesystemslib.rsa_keys._ENCRYPTION_DELIMITER + encryption_delimiter = ( + securesystemslib.rsa_keys._ENCRYPTION_DELIMITER # pylint: disable=protected-access + ) salt, iterations, hmac, iv, ciphertext = encrypted_rsa_key.split( encryption_delimiter ) diff --git a/tests/test_schema.py b/tests/test_schema.py index 580f6556..ede75251 100755 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -24,7 +24,7 @@ import securesystemslib.schema as SCHEMA -class TestSchema(unittest.TestCase): +class TestSchema(unittest.TestCase): # pylint: disable=missing-class-docstring def setUp(self): pass @@ -34,7 +34,7 @@ def tearDown(self): def test_Schema(self): # Test conditions for the instantation of classes that inherit # from class Schema(). - class NewSchema(SCHEMA.Schema): + class NewSchema(SCHEMA.Schema): # pylint: disable=abstract-method def __init__(self): pass @@ -46,7 +46,7 @@ class NewSchema2(SCHEMA.Schema): def __init__(self, string): self._string = string - def check_match(self, object): + def check_match(self, object): # pylint: disable=redefined-builtin if self._string != object: message = "Expected: " + repr(self._string) raise securesystemslib.exceptions.FormatError(message) @@ -443,7 +443,10 @@ def test_RegularExpression(self): ) self.assertTrue(re_schema_optional.matches("abc")) - self.assertTrue(re_schema_optional._re_name == "pattern") + self.assertTrue( + re_schema_optional._re_name # pylint: disable=protected-access + == "pattern" + ) # Test conditions for invalid arguments. self.assertFalse(re_schema.matches("Hello World")) diff --git a/tests/test_signer.py b/tests/test_signer.py index 1747fc4c..e87736cb 100644 --- a/tests/test_signer.py +++ b/tests/test_signer.py @@ -22,7 +22,9 @@ ) -class TestSSlibSigner(unittest.TestCase): +class TestSSlibSigner( + unittest.TestCase +): # pylint: disable=missing-class-docstring @classmethod def setUpClass(cls): cls.rsakey_dict = KEYS.generate_rsa_key() diff --git a/tests/test_storage.py b/tests/test_storage.py index 29c7bdf3..c0b24d81 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -24,14 +24,16 @@ import securesystemslib.storage -class TestStorage(unittest.TestCase): +class TestStorage(unittest.TestCase): # pylint: disable=missing-class-docstring def setUp(self): self.storage_backend = securesystemslib.storage.FilesystemBackend() self.temp_dir = tempfile.mkdtemp(dir=os.getcwd()) self.filepath = os.path.join(self.temp_dir, "testfile") with open(self.filepath, "wb") as test: test.write(b"testing") - self.fileobj = open(self.filepath, "rb") + self.fileobj = open( # pylint: disable=consider-using-with + self.filepath, "rb" + ) def tearDown(self): self.fileobj.close() @@ -41,7 +43,7 @@ def test_exceptions(self): try: with self.storage_backend.get("/none/existent/path") as file_object: file_object.read() - except Exception as exc: + except Exception as exc: # pylint: disable=broad-except self.assertIsInstance(exc, securesystemslib.exceptions.StorageError) self.assertRaises( diff --git a/tests/test_util.py b/tests/test_util.py index ed4f4975..55747e8b 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -19,23 +19,25 @@ import logging import os -import shutil +import shutil # pylint: disable=unused-import import stat -import sys +import sys # pylint: disable=unused-import import tempfile import timeit import unittest -import securesystemslib.exceptions as exceptions +import securesystemslib.exceptions as exceptions # pylint: disable=consider-using-from-import import securesystemslib.hash import securesystemslib.settings -import securesystemslib.unittest_toolbox as unittest_toolbox +import securesystemslib.unittest_toolbox as unittest_toolbox # pylint: disable=consider-using-from-import import securesystemslib.util logger = logging.getLogger(__name__) -class TestUtil(unittest_toolbox.Modified_TestCase): +class TestUtil( + unittest_toolbox.Modified_TestCase +): # pylint: disable=missing-class-docstring def setUp(self): unittest_toolbox.Modified_TestCase.setUp(self) self.temp_fileobj = tempfile.TemporaryFile() @@ -133,7 +135,7 @@ def test_B3_get_file_length(self): filepath = self.make_temp_data_file() # Computing the length of the tempfile. - digest_object = securesystemslib.hash.digest_filename( + digest_object = securesystemslib.hash.digest_filename( # pylint: disable=unused-variable filepath, algorithm="sha256" ) file_length = os.path.getsize(filepath) @@ -264,7 +266,11 @@ def test_B7_load_json_string(self): def test_B8_load_json_file(self): data = ["a", {"b": ["c", None, 30.3, 29]}] filepath = self.make_temp_file() - fileobj = open(filepath, "wt") + fileobj = ( + open( # pylint: disable=unspecified-encoding,consider-using-with + filepath, "wt" + ) + ) securesystemslib.util.json.dump(data, fileobj) fileobj.close() self.assertEqual(data, securesystemslib.util.load_json_file(filepath)) @@ -286,7 +292,11 @@ def test_B8_load_json_file(self): # Invalid JSON content. filepath_bad_data = self.make_temp_file() - fileobj = open(filepath_bad_data, "wt") + fileobj = ( + open( # pylint: disable=unspecified-encoding,consider-using-with + filepath_bad_data, "wt" + ) + ) fileobj.write("junk data") fileobj.close() @@ -356,7 +366,9 @@ def test_c5_unittest_toolbox_random_path(self): self.assertTrue( securesystemslib.formats.PATH_SCHEMA.matches(random_path) ) - self.assertTrue(10, len(random_path)) + self.assertTrue( # pylint: disable=redundant-unittest-assert + 10, len(random_path) + ) def test_digests_are_equal(self): digest = (