Add pylint (#892)

* Move mypy/flake8/isort config files to more 'natural' places.

* Add pylint.

* Look at no-member.

* Look at pointless-* and unnecessary-pass.

* Look at useless-*.

* Lint.
This commit is contained in:
Felix Fontein
2025-05-17 16:45:37 +02:00
committed by GitHub
parent 5fbf35df86
commit 990b40df3e
17 changed files with 681 additions and 54 deletions

615
.pylintrc Normal file
View File

@@ -0,0 +1,615 @@
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2025 Felix Fontein <felix@fontein.de>
[MAIN]
# Clear in-memory caches upon conclusion of linting. Useful if running pylint
# in a server-like mode.
clear-cache-post-run=no
# Load and enable all available extensions. Use --list-extensions to see a list
# all available extensions.
#enable-all-extensions=
# Specify a score threshold under which the program will exit with error.
fail-under=10
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use, and will cap the count on Windows to
# avoid hangs.
jobs=0
# Minimum Python version to use for version dependent checks. Will default to
# the version used to run pylint.
py-version=3.7
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
# In verbose mode, extra non-checker-related info will be displayed.
#verbose=
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# naming-style. If left empty, argument names will be checked with the set
# naming style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style. If left empty, attribute names will be checked with the set naming
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style. If left empty, class attribute names will be checked
# with the set naming style.
#class-attribute-rgx=
# Naming style matching correct class constant names.
class-const-naming-style=UPPER_CASE
# Regular expression matching correct class constant names. Overrides class-
# const-naming-style. If left empty, class constant names will be checked with
# the set naming style.
#class-const-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style. If left empty, class names will be checked with the set naming style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style. If left empty, constant names will be checked with the set naming
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# naming-style. If left empty, function names will be checked with the set
# naming style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style. If left empty, inline iteration names will be checked
# with the set naming style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=snake_case
# Regular expression matching correct method names. Overrides method-naming-
# style. If left empty, method names will be checked with the set naming style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style. If left empty, module names will be checked with the set naming style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Regular expression matching correct type alias names. If left empty, type
# alias names will be checked with the set naming style.
#typealias-rgx=
# Regular expression matching correct type variable names. If left empty, type
# variable names will be checked with the set naming style.
#typevar-rgx=
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style. If left empty, variable names will be checked with the set
# naming style.
#variable-rgx=
[CLASSES]
# Warn about protected attribute access inside special methods
check-protected-access-in-special-methods=no
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp,
asyncSetUp,
__post_init__
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=mcs
[DESIGN]
# List of regular expressions of class ancestor names to ignore when counting
# public methods (see R0903)
exclude-too-few-public-methods=
# List of qualified class names to ignore when counting class parents (see
# R0901)
ignored-parents=
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of positional arguments for function / method.
max-positional-arguments=5
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[EXCEPTIONS]
# Exceptions that will emit a warning when caught.
overgeneral-exceptions=builtins.BaseException,builtins.Exception
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=160
# Maximum number of lines in a module.
max-module-lines=1000
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[IMPORTS]
# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=
# Allow explicit reexports by alias from a package __init__.
allow-reexport-from-package=no
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=
# Output a graph (.gv or any supported image format) of external dependencies
# to the given file (report RP0402 must not be disabled).
ext-import-graph=
# Output a graph (.gv or any supported image format) of all (i.e. internal and
# external) dependencies to the given file (report RP0402 must not be
# disabled).
import-graph=
# Output a graph (.gv or any supported image format) of internal dependencies
# to the given file (report RP0402 must not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
# Couples of modules and preferred modules, separated by a comma.
preferred-modules=
[LOGGING]
# The type of string formatting that logging methods do. `old` means using %
# formatting, `new` is for `{}` formatting.
logging-format-style=old
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
# UNDEFINED.
confidence=HIGH,
CONTROL_FLOW,
INFERENCE,
INFERENCE_FAILURE,
UNDEFINED
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then re-enable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=raw-checker-failed,
bad-inline-option,
deprecated-pragma,
duplicate-code,
file-ignored,
import-outside-toplevel,
missing-class-docstring,
missing-function-docstring,
missing-module-docstring,
locally-disabled,
suppressed-message,
useless-suppression,
use-symbolic-message-instead,
use-implicit-booleaness-not-comparison,
use-implicit-booleaness-not-comparison-to-string,
use-implicit-booleaness-not-comparison-to-zero,
too-few-public-methods,
too-many-arguments,
too-many-boolean-expressions,
too-many-branches,
too-many-function-args,
too-many-instance-attributes,
too-many-lines,
too-many-locals,
too-many-nested-blocks,
too-many-positional-arguments,
too-many-return-statements,
too-many-statements,
ungrouped-imports,
useless-parent-delegation,
wrong-import-order,
wrong-import-position,
# To clean up:
arguments-differ,
attribute-defined-outside-init,
broad-exception-caught,
broad-exception-raised,
consider-using-dict-items,
consider-using-in,
consider-using-set-comprehension,
consider-using-with,
fixme,
inconsistent-return-statements,
invalid-name,
no-else-raise,
no-else-return,
possibly-used-before-assignment,
protected-access,
raise-missing-from,
redefined-argument-from-local,
redefined-builtin,
redefined-outer-name,
superfluous-parens,
super-with-arguments,
try-except-raise,
unknown-option-value,
unspecified-encoding,
unsupported-assignment-operation,
unsupported-binary-operation,
unused-argument,
unused-variable,
use-dict-literal,
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=
[METHOD_ARGS]
# List of qualified names (i.e., library.method) which require a timeout
# parameter e.g. 'requests.api.get,requests.api.post'
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
# Regular expression of note tags to take in consideration.
notes-rgx=
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit,argparse.parse_error
# Let 'consider-using-join' be raised when the separator to join on would be
# non-empty (resulting in expected fixes of the type: ``"- " + " -
# ".join(items)``)
suggest-join-with-non-empty-separator=yes
[REPORTS]
# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
# 'convention', and 'info' which contain the number of messages in each
# category, as well as 'statement' which is the total number of statements
# analyzed. This score is used by the global evaluation report (RP0004).
evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
msg-template=
# Set the output format. Available formats are: text, parseable, colorized,
# json2 (improved json format), json (old json format) and msvs (visual
# studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
#output-format=
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[SIMILARITIES]
# Comments are removed from the similarity computation
ignore-comments=yes
# Docstrings are removed from the similarity computation
ignore-docstrings=yes
# Imports are removed from the similarity computation
ignore-imports=yes
# Signatures are removed from the similarity computation
ignore-signatures=yes
# Minimum lines number of a similarity.
min-similarity-lines=4
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. No available dictionaries : You need to install
# both the python package and the system dependency for enchant to work.
spelling-dict=
# List of comma separated words that should be considered directives if they
# appear at the beginning of a comment and should not be checked.
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no
[STRING]
# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=no
# This flag controls whether the implicit-str-concat should generate a warning
# on implicit string concatenation in sequences defined over several lines.
check-str-concat-over-line-jumps=no
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of symbolic message names to ignore for Mixin members.
ignored-checks-for-mixins=no-member,
not-async-context-manager,
not-context-manager,
attribute-defined-outside-init
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
# Regex pattern to define which classes are considered mixins.
mixin-class-rgx=.*[Mm]ixin
# List of decorators that change the signature of a decorated function.
signature-mutators=
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of names allowed to shadow builtins
allowed-redefined-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io

View File

@@ -9,18 +9,19 @@
[sessions.lint] [sessions.lint]
run_isort = true run_isort = true
isort_config = "tests/nox-config-isort.cfg" isort_config = ".isort.cfg"
run_black = true run_black = true
run_flake8 = true run_flake8 = true
flake8_config = "tests/nox-config-flake8.ini" flake8_config = ".flake8"
run_pylint = false run_pylint = true
pylint_rcfile = ".pylintrc"
run_yamllint = true run_yamllint = true
yamllint_config = ".yamllint" yamllint_config = ".yamllint"
yamllint_config_plugins = ".yamllint-docs" yamllint_config_plugins = ".yamllint-docs"
yamllint_config_plugins_examples = ".yamllint-examples" yamllint_config_plugins_examples = ".yamllint-examples"
run_mypy = true run_mypy = true
mypy_ansible_core_package = "ansible-core>=2.19.0b3" mypy_ansible_core_package = "ansible-core>=2.19.0b3"
mypy_config = "tests/nox-config-mypy.ini" mypy_config = ".mypy.ini"
mypy_extra_deps = [ mypy_extra_deps = [
"cryptography", "cryptography",
"types-mock", "types-mock",

View File

@@ -13,23 +13,21 @@ import re
from ansible.module_utils.common.text.converters import to_bytes from ansible.module_utils.common.text.converters import to_bytes
""" # An ASN.1 serialized as a string in the OpenSSL format:
An ASN.1 serialized as a string in the OpenSSL format: # [modifier,]type[:value]
[modifier,]type[:value] #
# 'modifier':
modifier: # The modifier can be 'IMPLICIT:<tag_number><tag_class>,' or 'EXPLICIT:<tag_number><tag_class>' where IMPLICIT
The modifier can be 'IMPLICIT:<tag_number><tag_class>,' or 'EXPLICIT:<tag_number><tag_class>' where IMPLICIT # changes the tag of the universal value to encode and EXPLICIT prefixes its tag to the existing universal value.
changes the tag of the universal value to encode and EXPLICIT prefixes its tag to the existing universal value. # The tag_number must be set while the tag_class can be 'U', 'A', 'P', or 'C" for 'Universal', 'Application',
The tag_number must be set while the tag_class can be 'U', 'A', 'P', or 'C" for 'Universal', 'Application', # 'Private', or 'Context Specific' with C being the default.
'Private', or 'Context Specific' with C being the default. #
# 'type':
type: # The underlying ASN.1 type of the value specified. Currently only the following have been implemented:
The underlying ASN.1 type of the value specified. Currently only the following have been implemented: # UTF8: The value must be a UTF-8 encoded string.
UTF8: The value must be a UTF-8 encoded string. #
# 'value':
value: # The value to encode, the format of this value depends on the <type> specified.
The value to encode, the format of this value depends on the <type> specified.
"""
ASN1_STRING_REGEX = re.compile( ASN1_STRING_REGEX = re.compile(
r"^((?P<tag_type>IMPLICIT|EXPLICIT):(?P<tag_number>\d+)(?P<tag_class>U|A|P|C)?,)?" r"^((?P<tag_type>IMPLICIT|EXPLICIT):(?P<tag_number>\d+)(?P<tag_class>U|A|P|C)?,)?"
r"(?P<value_type>[\w\d]+):(?P<value>.*)" r"(?P<value_type>[\w\d]+):(?P<value>.*)"

View File

@@ -40,9 +40,8 @@ try:
_HAS_CRYPTOGRAPHY = True _HAS_CRYPTOGRAPHY = True
except ImportError: except ImportError:
_HAS_CRYPTOGRAPHY = False
# Error handled in the calling module. # Error handled in the calling module.
pass _HAS_CRYPTOGRAPHY = False
try: try:
import cryptography.hazmat.primitives.asymmetric.dh import cryptography.hazmat.primitives.asymmetric.dh
@@ -906,12 +905,13 @@ def _parse_pkcs12_35_0_0(
# Since load_key_and_certificates succeeded, it should not fail. # Since load_key_and_certificates succeeded, it should not fail.
pkcs12 = backend._ffi.gc( pkcs12 = backend._ffi.gc(
backend._lib.d2i_PKCS12_bio( backend._lib.d2i_PKCS12_bio(
backend._bytes_to_bio(pkcs12_bytes).bio, backend._ffi.NULL backend._bytes_to_bio(pkcs12_bytes).bio, # pylint: disable=no-member
backend._ffi.NULL,
), ),
backend._lib.PKCS12_free, backend._lib.PKCS12_free,
) )
certificate_x509_ptr = backend._ffi.new("X509 **") certificate_x509_ptr = backend._ffi.new("X509 **")
with backend._zeroed_null_terminated_buf( with backend._zeroed_null_terminated_buf( # pylint: disable=no-member
to_bytes(passphrase) if passphrase is not None else None to_bytes(passphrase) if passphrase is not None else None
) as passphrase_buffer: ) as passphrase_buffer:
backend._lib.PKCS12_parse( backend._lib.PKCS12_parse(

View File

@@ -114,12 +114,10 @@ class CertificateBackend(metaclass=abc.ABCMeta):
@abc.abstractmethod @abc.abstractmethod
def generate_certificate(self) -> None: def generate_certificate(self) -> None:
"""(Re-)Generate certificate.""" """(Re-)Generate certificate."""
pass
@abc.abstractmethod @abc.abstractmethod
def get_certificate_data(self) -> bytes: def get_certificate_data(self) -> bytes:
"""Return bytes for self.cert.""" """Return bytes for self.cert."""
pass
def set_existing(self, certificate_bytes: bytes | None) -> None: def set_existing(self, certificate_bytes: bytes | None) -> None:
"""Set existing certificate bytes. None indicates that the key does not exist.""" """Set existing certificate bytes. None indicates that the key does not exist."""

View File

@@ -140,7 +140,9 @@ class EntrustCertificateBackend(CertificateBackend):
} }
try: try:
result = self.ecs_client.NewCertRequest(Body=body) result = self.ecs_client.NewCertRequest( # pylint: disable=no-member
Body=body
)
self.trackingId = result.get("trackingId") self.trackingId = result.get("trackingId")
except RestOperationException as e: except RestOperationException as e:
self.module.fail_json( self.module.fail_json(
@@ -204,9 +206,11 @@ class EntrustCertificateBackend(CertificateBackend):
# If a trackingId is not already defined (from the result of a generate) # If a trackingId is not already defined (from the result of a generate)
# use the serial number to identify the tracking Id # use the serial number to identify the tracking Id
if self.trackingId is None and serial_number is not None: if self.trackingId is None and serial_number is not None:
cert_results = self.ecs_client.GetCertificates( cert_results = (
serialNumber=serial_number self.ecs_client.GetCertificates( # pylint: disable=no-member
).get("certificates", {}) serialNumber=serial_number
).get("certificates", {})
)
# Finding 0 or more than 1 result is a very unlikely use case, it simply means we cannot perform additional checks # Finding 0 or more than 1 result is a very unlikely use case, it simply means we cannot perform additional checks
# on the 'state' as returned by Entrust Certificate Services (ECS). The general certificate validity is # on the 'state' as returned by Entrust Certificate Services (ECS). The general certificate validity is
@@ -216,7 +220,9 @@ class EntrustCertificateBackend(CertificateBackend):
if self.trackingId is not None: if self.trackingId is not None:
cert_details.update( cert_details.update(
self.ecs_client.GetCertificate(trackingId=self.trackingId) self.ecs_client.GetCertificate( # pylint: disable=no-member
trackingId=self.trackingId
)
) )
return cert_details return cert_details

View File

@@ -132,7 +132,6 @@ class PrivateKeyBackend(metaclass=abc.ABCMeta):
@abc.abstractmethod @abc.abstractmethod
def generate_private_key(self) -> None: def generate_private_key(self) -> None:
"""(Re-)Generate private key.""" """(Re-)Generate private key."""
pass
def convert_private_key(self) -> None: def convert_private_key(self) -> None:
"""Convert existing private key (self.existing_private_key) to new private key (self.private_key). """Convert existing private key (self.existing_private_key) to new private key (self.private_key).

View File

@@ -91,7 +91,6 @@ class PrivateKeyConvertBackend(metaclass=abc.ABCMeta):
@abc.abstractmethod @abc.abstractmethod
def get_private_key_data(self) -> bytes: def get_private_key_data(self) -> bytes:
"""Return bytes for self.src_private_key in output format.""" """Return bytes for self.src_private_key in output format."""
pass
def set_existing_destination(self, *, privatekey_bytes: bytes | None) -> None: def set_existing_destination(self, *, privatekey_bytes: bytes | None) -> None:
"""Set existing private key bytes. None indicates that the key does not exist.""" """Set existing private key bytes. None indicates that the key does not exist."""

View File

@@ -31,7 +31,6 @@ class GPGRunner(metaclass=abc.ABCMeta):
Raises a ``GPGError`` in case of errors. Raises a ``GPGError`` in case of errors.
""" """
pass
def get_fingerprint_from_stdout(*, stdout: str) -> str: def get_fingerprint_from_stdout(*, stdout: str) -> str:

View File

@@ -221,6 +221,7 @@ def add_crypto_information(module: AnsibleModule) -> dict[str, t.Any]:
has_dsa = True has_dsa = True
try: try:
# added later in 1.5 # added later in 1.5
# pylint: disable-next=pointless-statement
cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey.sign cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey.sign
has_dsa_sign = True has_dsa_sign = True
except AttributeError: except AttributeError:
@@ -238,6 +239,7 @@ def add_crypto_information(module: AnsibleModule) -> dict[str, t.Any]:
has_rsa = True has_rsa = True
try: try:
# added later in 1.4 # added later in 1.4
# pylint: disable-next=pointless-statement
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey.sign cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey.sign
has_rsa_sign = True has_rsa_sign = True
except AttributeError: except AttributeError:
@@ -263,6 +265,7 @@ def add_crypto_information(module: AnsibleModule) -> dict[str, t.Any]:
has_ed25519 = True has_ed25519 = True
try: try:
# added with the primitive in 2.6 # added with the primitive in 2.6
# pylint: disable-next=pointless-statement
cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.sign cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.sign
has_ed25519_sign = True has_ed25519_sign = True
except AttributeError: except AttributeError:
@@ -286,6 +289,7 @@ def add_crypto_information(module: AnsibleModule) -> dict[str, t.Any]:
has_ed448 = True has_ed448 = True
try: try:
# added with the primitive in 2.6 # added with the primitive in 2.6
# pylint: disable-next=pointless-statement
cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey.sign cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey.sign
has_ed448_sign = True has_ed448_sign = True
except AttributeError: except AttributeError:
@@ -302,6 +306,7 @@ def add_crypto_information(module: AnsibleModule) -> dict[str, t.Any]:
try: try:
# added later in 2.5 # added later in 2.5
# pylint: disable-next=pointless-statement
cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.private_bytes cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.private_bytes
full = True full = True
except AttributeError: except AttributeError:
@@ -351,6 +356,7 @@ def add_crypto_information(module: AnsibleModule) -> dict[str, t.Any]:
has_ec = True has_ec = True
try: try:
# added later in 1.5 # added later in 1.5
# pylint: disable-next=pointless-statement
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey.sign cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey.sign
has_ec_sign = True has_ec_sign = True
except AttributeError: except AttributeError:

View File

@@ -658,7 +658,7 @@ class EcsCertificate:
except SessionConfigurationException as e: except SessionConfigurationException as e:
module.fail_json(msg=f"Failed to initialize Entrust Provider: {e}") module.fail_json(msg=f"Failed to initialize Entrust Provider: {e}")
try: try:
self.ecs_client.GetAppVersion() self.ecs_client.GetAppVersion() # pylint: disable=no-member
except RestOperationException as e: except RestOperationException as e:
module.fail_json( module.fail_json(
msg=f"Please verify credential information. Received exception when testing ECS connection: {e.message}" msg=f"Please verify credential information. Received exception when testing ECS connection: {e.message}"
@@ -732,19 +732,21 @@ class EcsCertificate:
# Use serial_number to identify if certificate is an Entrust Certificate # Use serial_number to identify if certificate is an Entrust Certificate
# with an associated tracking ID # with an associated tracking ID
serial_number = f"{self.cert.serial_number:X}" serial_number = f"{self.cert.serial_number:X}"
cert_results = self.ecs_client.GetCertificates( cert_results = self.ecs_client.GetCertificates( # pylint: disable=no-member
serialNumber=serial_number serialNumber=serial_number
).get("certificates", {}) ).get("certificates", {})
if len(cert_results) == 1: if len(cert_results) == 1:
self.tracking_id = cert_results[0].get("trackingId") self.tracking_id = cert_results[0].get("trackingId")
except RestOperationException: except RestOperationException:
# If we fail to find a cert by serial number, that's fine, we just do not set self.tracking_id # If we fail to find a cert by serial number, that's fine, we just do not set self.tracking_id
return pass
def set_cert_details(self, module): def set_cert_details(self, module):
try: try:
self.cert_details = self.ecs_client.GetCertificate( self.cert_details = (
trackingId=self.tracking_id self.ecs_client.GetCertificate( # pylint: disable=no-member
trackingId=self.tracking_id
)
) )
self.cert_status = self.cert_details.get("status") self.cert_status = self.cert_details.get("status")
self.serial_number = self.cert_details.get("serialNumber") self.serial_number = self.cert_details.get("serialNumber")
@@ -828,15 +830,23 @@ class EcsCertificate:
try: try:
if self.request_type == "validate_only": if self.request_type == "validate_only":
body["validateOnly"] = "true" body["validateOnly"] = "true"
result = self.ecs_client.NewCertRequest(Body=body) result = (
self.ecs_client.NewCertRequest( # pylint: disable=no-member
Body=body
)
)
if self.request_type == "new": if self.request_type == "new":
result = self.ecs_client.NewCertRequest(Body=body) result = (
self.ecs_client.NewCertRequest( # pylint: disable=no-member
Body=body
)
)
elif self.request_type == "renew": elif self.request_type == "renew":
result = self.ecs_client.RenewCertRequest( result = self.ecs_client.RenewCertRequest( # pylint: disable=no-member
trackingId=self.tracking_id, Body=body trackingId=self.tracking_id, Body=body
) )
elif self.request_type == "reissue": elif self.request_type == "reissue":
result = self.ecs_client.ReissueCertRequest( result = self.ecs_client.ReissueCertRequest( # pylint: disable=no-member
trackingId=self.tracking_id, Body=body trackingId=self.tracking_id, Body=body
) )
self.tracking_id = result.get("trackingId") self.tracking_id = result.get("trackingId")

View File

@@ -276,7 +276,7 @@ class EcsDomain:
except SessionConfigurationException as e: except SessionConfigurationException as e:
module.fail_json(msg=f"Failed to initialize Entrust Provider: {e}") module.fail_json(msg=f"Failed to initialize Entrust Provider: {e}")
try: try:
self.ecs_client.GetAppVersion() self.ecs_client.GetAppVersion() # pylint: disable=no-member
except RestOperationException as e: except RestOperationException as e:
module.fail_json( module.fail_json(
msg=f"Please verify credential information. Received exception when testing ECS connection: {e.message}" msg=f"Please verify credential information. Received exception when testing ECS connection: {e.message}"
@@ -310,7 +310,7 @@ class EcsDomain:
def check(self, module): def check(self, module):
try: try:
domain_details = self.ecs_client.GetDomain( domain_details = self.ecs_client.GetDomain( # pylint: disable=no-member
clientId=module.params["client_id"], domain=module.params["domain_name"] clientId=module.params["client_id"], domain=module.params["domain_name"]
) )
self.set_domain_details(domain_details) self.set_domain_details(domain_details)
@@ -355,18 +355,18 @@ class EcsDomain:
body["domainName"] = module.params["domain_name"] body["domainName"] = module.params["domain_name"]
try: try:
if not self.domain_status: if not self.domain_status:
self.ecs_client.AddDomain( self.ecs_client.AddDomain( # pylint: disable=no-member
clientId=module.params["client_id"], Body=body clientId=module.params["client_id"], Body=body
) )
else: else:
self.ecs_client.ReverifyDomain( self.ecs_client.ReverifyDomain( # pylint: disable=no-member
clientId=module.params["client_id"], clientId=module.params["client_id"],
domain=module.params["domain_name"], domain=module.params["domain_name"],
Body=body, Body=body,
) )
time.sleep(5) time.sleep(5)
result = self.ecs_client.GetDomain( result = self.ecs_client.GetDomain( # pylint: disable=no-member
clientId=module.params["client_id"], clientId=module.params["client_id"],
domain=module.params["domain_name"], domain=module.params["domain_name"],
) )
@@ -393,7 +393,7 @@ class EcsDomain:
): ):
break break
time.sleep(10) time.sleep(10)
result = self.ecs_client.GetDomain( result = self.ecs_client.GetDomain( # pylint: disable=no-member
clientId=module.params["client_id"], clientId=module.params["client_id"],
domain=module.params["domain_name"], domain=module.params["domain_name"],
) )

View File

@@ -188,7 +188,6 @@ class DHParameterBase:
@abc.abstractmethod @abc.abstractmethod
def _do_generate(self, module: AnsibleModule) -> None: def _do_generate(self, module: AnsibleModule) -> None:
"""Actually generate the DH params.""" """Actually generate the DH params."""
pass
def generate(self, module: AnsibleModule) -> None: def generate(self, module: AnsibleModule) -> None:
"""Generate DH params.""" """Generate DH params."""

View File

@@ -205,7 +205,6 @@ def test_invalid_user_key_params(
result = True result = True
except Exception as e: except Exception as e:
print(e) print(e)
pass
assert result assert result
@@ -225,7 +224,6 @@ def test_invalid_key_sizes(
result = True result = True
except Exception as e: except Exception as e:
print(e) print(e)
pass
assert result assert result
@@ -239,7 +237,6 @@ def test_valid_comment_update() -> None:
pair.comment = new_comment pair.comment = new_comment
except Exception as e: except Exception as e:
print(e) print(e)
pass
assert ( assert (
pair.comment == new_comment pair.comment == new_comment