From df3c585f5fbbc3bafceff56aaedbfde5e9c987c6 Mon Sep 17 00:00:00 2001 From: Andreas Maier Date: Wed, 3 Jul 2024 05:48:42 +0200 Subject: [PATCH] Added separate pylint run Test: Added a separate pylint run (in addition to the one in the Ansible sanity test), because it can be run on the test sources as well, and because the santy test pylint has important checks disabled. (issue #1007) Details: * Added a new make target 'pylint'. * Added 'make pylnt' to the test workflow. * Fixed issues reported by pylint (many). Signed-off-by: Andreas Maier --- .github/workflows/test.yml | 6 + .pylintrc | 676 ++++++++++++++++++ Makefile | 18 +- docs/source/release_notes.rst | 4 + plugins/module_utils/common.py | 35 +- plugins/modules/zhmc_adapter.py | 9 +- plugins/modules/zhmc_adapter_list.py | 5 +- plugins/modules/zhmc_console.py | 5 +- plugins/modules/zhmc_cpc.py | 6 +- plugins/modules/zhmc_cpc_list.py | 5 +- plugins/modules/zhmc_crypto_attachment.py | 9 +- plugins/modules/zhmc_hba.py | 6 +- .../modules/zhmc_ldap_server_definition.py | 16 +- .../zhmc_ldap_server_definition_list.py | 5 +- plugins/modules/zhmc_lpar.py | 35 +- plugins/modules/zhmc_lpar_list.py | 5 +- plugins/modules/zhmc_lpar_messages.py | 5 +- plugins/modules/zhmc_nic.py | 7 +- plugins/modules/zhmc_nic_list.py | 5 +- plugins/modules/zhmc_partition.py | 16 +- plugins/modules/zhmc_partition_list.py | 5 +- plugins/modules/zhmc_partition_messages.py | 5 +- plugins/modules/zhmc_password_rule.py | 15 +- plugins/modules/zhmc_password_rule_list.py | 5 +- plugins/modules/zhmc_session.py | 6 +- plugins/modules/zhmc_storage_group.py | 8 +- .../modules/zhmc_storage_group_attachment.py | 6 +- plugins/modules/zhmc_storage_volume.py | 20 +- plugins/modules/zhmc_user.py | 14 +- plugins/modules/zhmc_user_list.py | 5 +- plugins/modules/zhmc_user_role.py | 31 +- plugins/modules/zhmc_user_role_list.py | 5 +- plugins/modules/zhmc_versions.py | 5 +- plugins/modules/zhmc_virtual_function.py | 6 +- tests/end2end/test_zhmc_adapter.py | 12 +- tests/end2end/test_zhmc_adapter_list.py | 10 +- tests/end2end/test_zhmc_cpc.py | 7 +- tests/end2end/test_zhmc_cpc_list.py | 7 +- .../test_zhmc_ldap_server_definition.py | 19 +- .../test_zhmc_ldap_server_definition_list.py | 7 +- tests/end2end/test_zhmc_lpar.py | 16 +- tests/end2end/test_zhmc_lpar_list.py | 7 +- tests/end2end/test_zhmc_lpar_messages.py | 7 +- tests/end2end/test_zhmc_partition.py | 46 +- tests/end2end/test_zhmc_partition_list.py | 7 +- tests/end2end/test_zhmc_partition_messages.py | 7 +- tests/end2end/test_zhmc_password_rule.py | 15 +- tests/end2end/test_zhmc_password_rule_list.py | 7 +- tests/end2end/test_zhmc_session.py | 8 +- tests/end2end/test_zhmc_user.py | 18 +- tests/end2end/test_zhmc_user_list.py | 7 +- tests/end2end/test_zhmc_user_role.py | 15 +- tests/end2end/test_zhmc_user_role_list.py | 7 +- tests/end2end/test_zhmc_versions.py | 7 +- tests/function/test_func_cpc.py | 21 +- tests/function/test_func_lpar.py | 15 +- tests/function/test_func_partition.py | 30 +- tests/unit/test_common.py | 1 + tests/unit/test_hba.py | 438 ++++++------ tests/unit/test_nic.py | 438 ++++++------ tests/unit/test_partition.py | 580 ++++++++------- tests/unit/test_virtual_function.py | 440 ++++++------ 62 files changed, 1996 insertions(+), 1217 deletions(-) create mode 100644 .pylintrc diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 673aaa69a..43d2431e1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -195,6 +195,12 @@ jobs: RUN_TYPE: ${{ steps.set-run-type.outputs.result }} run: | make check + - name: Run pylint + env: + PACKAGE_LEVEL: ${{ matrix.package_level }} + RUN_TYPE: ${{ steps.set-run-type.outputs.result }} + run: | + make pylint - name: Run sanity env: PACKAGE_LEVEL: ${{ matrix.package_level }} diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 000000000..f2baa1226 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,676 @@ +# +# PyLint configuration file for the project +# +# Originally generated by pylint 2.14.1, now manually maintained. +# Intended for pylint >= 2.5.2 (Python >= 3.5). + +[MAIN] + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, checkers without error messages are disabled and for others, +# only the ERROR messages are displayed, and no reports are done by default. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold to be exceeded before program exits with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=.svn,.git + +# Add files or directories matching the regex patterns to the ignore-list. The +# regex matches against paths and can be in Posix or Windows format. +ignore-paths= + +# Files or directories matching the regex patterns are skipped. The regex +# matches against base names, not paths. The default value ignores Emacs file +# locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +# Note: Modules that create modules at run time cauase pylint to raise +# "no-name-in-module" and/or "import-error". Such modules can be put +# on the module ignore list. For details, see +# https://bitbucket.org/logilab/pylint/issues/223/ignored-modules-should-turn-no-name-in +ignored-modules=distutils, + six, + builtins, + urllib, + lxml, + lxml.etree, + ssl, + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins=pylint.extensions.no_self_use + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.9 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# 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= + + +[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. +# Note: Doc is at http://docs.pylint.org/output.html#reports-section +# Note: This format only affects output format text, but not html. +# Note: The default format is: +# {C}:{line:3d},{column:2d}: {msg} ({symbol}) +# Note: The vim quickfix support by default recognizes the following format: +# {path}:{line}: ... +# {path}:{line}: {msg_id} {obj}: {msg} +# Note: Usage with Geany editor: +# use output-format=parseable +# No special message format. +msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW (new in 2.13), INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence= + +# 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". +# Note: The too-many-* messages are excluded temporarily, and should be dealt +# with at some point. +# Note: wildcard related messages are excluded because the original external +# interface uses wildcard imports and we cannot change that without +# breaking compatibility. We could move the message control statements +# into the source code, though. +# Note: messages are described here: http://pylint-messages.wikidot.com/all-messages +disable=I0011, + too-many-locals, too-many-branches, too-many-statements, + too-many-lines, too-many-public-methods, + too-many-nested-blocks, too-many-return-statements, too-many-arguments, + wildcard-import, unused-wildcard-import, + superfluous-parens, useless-object-inheritance, + consider-using-set-comprehension, unnecessary-pass, useless-return, + raise-missing-from, consider-using-f-string, + super-with-arguments, duplicate-string-formatting-argument, + consider-using-generator, bad-option-value, redundant-u-string-prefix, + use-implicit-booleaness-not-comparison, use-dict-literal, + missing-module-docstring, wrong-import-position, redefined-builtin, + try-except-raise, + +# 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= + + +[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 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 'python-enchant' package. +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 + + +[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= + + +[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= + + +[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, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# 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=cls + + +[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=^_$|^dummy_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.* + +# 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 + + +[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*(# )??$ + +# 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 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= + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=builtins.BaseException, + builtins.Exception + + +[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 + + +[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=200 + + +[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=8 + +# Maximum number of attributes for a class (see R0902). +# TODO AM: Are these just variables, without methods? class & instance? including private? including inherited? +max-attributes=30 + +# 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=15 + +# Maximum number of locals for function / method body. +max-locals=20 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# 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). +# TODO AM: including inherited? +min-public-methods=2 + + +[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 + + +[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. +# Note: The expression below allows "lower_case_with_underscores" and +# "mixedCaseWithoutUnderscores"; leading underscores are NOT allowed, +# but one trailing underscore is allowed to avoid conflists with built-in +# names. +# Names matching this expression are compatible with PEP-8. +argument-rgx=([a-z][a-z0-9_]{0,28}[a-z0-9]|[a-z][a-zA-Z0-9]{1,29})_{0,1}$ + +# 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. +# Note: The expression below allows "lower_case_with_underscores" and +# "mixedCaseWithoutUnderscores"; leading underscores for privacy are allowed. +# Names matching this expression are compatible with PEP-8. +attr-rgx=(_{0,1}([a-z][a-z0-9_]{0,28}[a-z0-9]|[a-z][a-zA-Z0-9]{1,29})|__[a-z_]+__)$ + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata, + l, + O, + I, + +# 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. +# Note: The expression below allows "UPPER_CASE_WITH_UNDERSCORES" for constants, +# and "lower_case_with_underscores" and "mixedCaseWithoutUnderscores" for +# other variables; leading underscores for privacy are allowed. +# Names matching this expression are compatible with PEP-8. +class-attribute-rgx=_{0,2}([A-Z][A-Z0-9_]{0,38}[A-Z0-9]|[a-z][a-z0-9_]{0,38}[a-z0-9]|[a-z][a-zA-Z0-9]{0,39}|__[a-z_]+__)$ + +# 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. +# Note: Names matching this expression are compatible with PEP-8, but PEP-8 also +# allows that class names for callable classes can use function name syntax. +# This is not reflected in this regexp; callable classes that follow that +# convention should disable PyLint message C0103. +class-rgx=(_{0,1}[A-Z][a-zA-Z0-9]{1,39}|__[a-z_]+__)$ + +# 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. +# Note: The expression below allows "UPPER_CASE_WITH_UNDERSCORES"; leading +# underscores for privacy are allowed. +# Names matching this expression are compatible with PEP-8. +const-rgx=(_{0,1}[A-Z][A-Z0-9_]{0,38}[A-Z0-9]|__[a-z_]+__)$ + +# 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. +# Note: The expression below allows "lower_case_with_underscores" and +# "mixedCaseWithoutUnderscores"; leading underscores for privacy as well as +# double trailing underscores are allowed. +# Names matching this expression are compatible with PEP-8. +function-rgx=(_{0,1}([a-z][a-z0-9_]{0,38}[a-z0-9]|[a-z][a-zA-Z0-9]{1,39})|__[a-z_]+__)$ +# TODO AM: Verify whether two leading underscores are allowed / supported with name mangling. + +# Good variable names which should always be accepted, separated by a comma. +good-names=_,f,i,j,k,m,n,__all__,__name__,__version__ + +# 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. +# Note: The expression below allows "lower_case_with_underscores" and +# "mixedCaseWithoutUnderscores"; leading underscores for privacy are allowed. +inlinevar-rgx=_{0,1}([a-z][a-z0-9_]{0,28}[a-z0-9]|[a-z][a-zA-Z0-9]{0,29})$ + +# 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. +# Note: The expression below allows "lower_case_with_underscores" and +# "mixedCaseWithoutUnderscores"; leading underscores for privacy as well as +# double trailing underscores are allowed. +# Names matching this expression are compatible with PEP-8. +method-rgx=(_{0,1}([a-z][a-z0-9_]{0,38}[a-z0-9]|[a-z][a-zA-Z0-9]{1,39})|__[a-z_]+__)$ + +# 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. +# Note: Names matching this expression are compatible with PEP-8. +module-rgx=(_{0,1}[a-z][a-z0-9_]{0,38}[a-z0-9]|__[a-z_]+__)$ + +# 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 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. +# Note: The expression below allows "UPPER_CASE_WITH_UNDERSCORES" for constants, +# and "lower_case_with_underscores" and "mixedCaseWithoutUnderscores" for +# other variables; one leading underscore is allowed, and one trailing +# underscore is allowed to avoid conflists with built-in names. +# Names matching this expression are compatible with PEP-8. +variable-rgx=_{0,1}([A-Z]([A-Z0-9_]{0,38}[A-Z0-9])?|[a-z]([a-z0-9_]{0,38}[a-z0-9])?|[a-z]([a-zA-Z0-9]{1,39})?)_{0,1}$ diff --git a/Makefile b/Makefile index a433314af..e7b245abd 100644 --- a/Makefile +++ b/Makefile @@ -113,6 +113,12 @@ default_testhmc := default # Flake8 options flake8_opts := --max-line-length 160 --config /dev/null --ignore E402,E741,W503,W504 +# PyLint config file +pylint_rc_file := .pylintrc + +# PyLint additional options +pylint_opts := --disable=fixme + # Sanity test directory # Note: 'ansible-test sanity' requires the collection to be tested to be # located in {...}/collections/ansible_collections/{namespace}/{name}. @@ -130,9 +136,9 @@ safety_install_policy_file := .safety-policy-install.yml safety_develop_policy_file := .safety-policy-develop.yml # Packages whose dependencies are checked using pip-missing-reqs -# ansible_test and pylint are checked only on officially supported Python versions +# ansible_test is checked only on officially supported Python versions ifeq ($(python_m_n_version),3.8) - check_reqs_packages := ansible pip_check_reqs pytest coverage coveralls flake8 sphinx ansible_doc_extractor + check_reqs_packages := ansible pip_check_reqs pytest coverage coveralls flake8 sphinx ansible_doc_extractor pylint else ifeq ($(python_m_n_version),3.9) check_reqs_packages := ansible pip_check_reqs pytest coverage coveralls flake8 sphinx ansible_doc_extractor ansible_test pylint else ifeq ($(python_m_n_version),3.10) @@ -199,6 +205,7 @@ help: @echo ' develop - Set up the development environment' @echo ' dist - Build the collection distribution archive in: $(dist_dir)' @echo ' check - Run flake8' + @echo " pylint - Run PyLint on sources" @echo ' sanity - Run Ansible sanity tests (includes pep8, pylint, validate-modules)' @echo ' ansible_lint - Run ansible-lint on distribution archive (and built it)' @echo ' safety - Run safety for install and all' @@ -238,7 +245,7 @@ help: @echo ' ansible-playbook playbooks/....' .PHONY: all -all: install develop dist safety bandit check sanity ansible_lint check_reqs docs docslocal linkcheck test end2end_mocked +all: install develop dist safety bandit check pylint sanity ansible_lint check_reqs docs docslocal linkcheck test end2end_mocked @echo '$@ done.' .PHONY: install @@ -269,6 +276,11 @@ check: _check_version $(done_dir)/develop_$(pymn)_$(PACKAGE_LEVEL).done flake8 $(flake8_opts) $(src_py_dir) $(test_dir) @echo '$@ done.' +.PHONY: pylint +pylint: _check_version $(done_dir)/develop_$(pymn)_$(PACKAGE_LEVEL).done $(pylint_rc_file) $(src_py_files) $(test_py_files) + pylint $(pylint_opts) --rcfile=$(pylint_rc_file) --output-format=text $(src_py_files) $(test_py_files) + @echo '$@ done.' + .PHONY: safety safety: $(done_dir)/safety_develop_$(pymn)_$(PACKAGE_LEVEL).done $(done_dir)/safety_install_$(pymn)_$(PACKAGE_LEVEL).done @echo "Makefile: $@ done." diff --git a/docs/source/release_notes.rst b/docs/source/release_notes.rst index 4383e2e7d..b0709dcde 100644 --- a/docs/source/release_notes.rst +++ b/docs/source/release_notes.rst @@ -104,6 +104,10 @@ Availability: `AutomationHub`_, `Galaxy`_, `GitHub`_ 'state=active,loaded'. For backwards compatibility, its default value is True. (issue #986) +* Test: Added a separate pylint run (in addition to the one in the Ansible + sanity test), because it can be run on the test sources as well, and because + the santy test pylint has important checks disabled. (issue #1007) + **Cleanup:** * Modernized the code to match the minimum Python version 3.8 (use of f-strings, diff --git a/plugins/module_utils/common.py b/plugins/module_utils/common.py index bad102065..b0d63e8d5 100644 --- a/plugins/module_utils/common.py +++ b/plugins/module_utils/common.py @@ -383,15 +383,18 @@ def stop_partition(logger, partition, check_mode): turns = 0 while turns < max_turns: turns += 1 + if status in PART_BAD_STATUSES: raise StatusError( f"CPC {partition.manager.cpc.name!r} has issues; partition " f"{partition.name!r} has bad status: {status!r}") - elif status in ('stopped', 'reservation-error'): + + if status in ('stopped', 'reservation-error'): logger.debug("Partition %r on CPC %r is now in status %r", partition.name, partition.manager.cpc.name, status) break - elif status == 'starting': + + if status == 'starting': logger.debug("Waiting for completion of starting of partition %r " "on CPC %r", partition.name, partition.manager.cpc.name) @@ -490,15 +493,18 @@ def start_partition(logger, partition, check_mode): tried_start = False while turns < max_turns: turns += 1 + if status in PART_BAD_STATUSES: raise StatusError( f"CPC {partition.manager.cpc.name!r} has issues; partition " f"{partition.name!r} has bad status: {status!r}") - elif status in ('active', 'degraded'): + + if status in ('active', 'degraded'): logger.debug("Partition %r on CPC %r is now in status %r", partition.name, partition.manager.cpc.name, status) break - elif status == 'stopping': + + if status == 'stopping': logger.debug("Waiting for completion of stopping of partition %r " "on CPC %r", partition.name, partition.manager.cpc.name) @@ -608,11 +614,13 @@ def wait_for_transition_completion(logger, partition): turns = 0 while turns < max_turns: turns += 1 + if status in PART_BAD_STATUSES: raise StatusError( f"CPC {partition.manager.cpc.name!r} has issues; partition " f"{partition.name!r} has bad status: {status!r}") - elif status == 'stopping': + + if status == 'stopping': logger.debug("Waiting for completion of stopping of partition %r " "on CPC %r", partition.name, partition.manager.cpc.name) @@ -1015,16 +1023,19 @@ def to_unicode(value): uval = to_unicode(val) list_uval.append(uval) return list_uval - elif isinstance(value, bytes): + + if isinstance(value, bytes): return value.decode('utf-8') - elif isinstance(value, str): + + if isinstance(value, str): return value - elif value is None: + + if value is None: return None - else: - raise TypeError( - f"Value of {type(value)} cannot be converted to unicode: " - f"{value!r}") + + raise TypeError( + f"Value of {type(value)} cannot be converted to unicode: " + f"{value!r}") def process_normal_property( diff --git a/plugins/modules/zhmc_adapter.py b/plugins/modules/zhmc_adapter.py index 9665ba7ea..76908924e 100644 --- a/plugins/modules/zhmc_adapter.py +++ b/plugins/modules/zhmc_adapter.py @@ -352,7 +352,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -506,6 +506,7 @@ def process_properties(adapter, params): for prop_name in input_props: try: + # pylint: disable=unused-variable allowed, create, update, update_active, eq_func, type_cast = \ ZHMC_ADAPTER_PROPERTIES[prop_name] except KeyError: @@ -629,6 +630,7 @@ def ensure_set(params, check_mode): # It was identified by name or match properties, so it does exist. # Update its properties and change adapter and crypto type, if # needed. + # pylint: disable=unused-variable create_props, update_props, chg_adapter_type, chg_crypto_type = \ process_properties(adapter, params) @@ -734,6 +736,7 @@ def ensure_present(params, check_mode): f"creating Hipersockets adapter {adapter_name!r} " "(must specify 'hipersockets').") + # pylint: disable=unused-variable create_props, update_props, _chg_adapter_type, _chg_crypto_type = \ process_properties(adapter, params) @@ -872,6 +875,7 @@ def ensure_absent(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Identify the target CPC and return facts about the target CPC and its child resources. @@ -923,6 +927,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -947,7 +952,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_adapter_list.py b/plugins/modules/zhmc_adapter_list.py index 4b101f29b..fdc6cfd98 100644 --- a/plugins/modules/zhmc_adapter_list.py +++ b/plugins/modules/zhmc_adapter_list.py @@ -281,7 +281,7 @@ missing_required_lib, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -434,6 +434,7 @@ def perform_list(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -461,7 +462,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_console.py b/plugins/modules/zhmc_console.py index 08b3c8ee4..6c62fa37e 100644 --- a/plugins/modules/zhmc_console.py +++ b/plugins/modules/zhmc_console.py @@ -239,7 +239,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -374,6 +374,7 @@ def perform_task(module): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -398,7 +399,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_cpc.py b/plugins/modules/zhmc_cpc.py index de34c0099..ba3e7bc23 100644 --- a/plugins/modules/zhmc_cpc.py +++ b/plugins/modules/zhmc_cpc.py @@ -418,7 +418,7 @@ common_fail_on_import_errors, pull_properties, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -513,6 +513,7 @@ def process_properties(cpc, params): for prop_name in input_props: try: + # pylint: disable=unused-variable allowed, create, update, update_active, eq_func, type_cast = \ ZHMC_CPC_PROPERTIES[prop_name] except KeyError: @@ -855,6 +856,7 @@ def perform_task(module): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -883,7 +885,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_cpc_list.py b/plugins/modules/zhmc_cpc_list.py index a85bbb472..8d2369b4c 100644 --- a/plugins/modules/zhmc_cpc_list.py +++ b/plugins/modules/zhmc_cpc_list.py @@ -224,7 +224,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -295,6 +295,7 @@ def perform_list(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -315,7 +316,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_crypto_attachment.py b/plugins/modules/zhmc_crypto_attachment.py index 49cfa558b..085341ee8 100644 --- a/plugins/modules/zhmc_crypto_attachment.py +++ b/plugins/modules/zhmc_crypto_attachment.py @@ -377,7 +377,7 @@ try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -579,7 +579,8 @@ def ensure_attached(params, check_mode): raise ParameterError( "The 'adapter_count' parameter must be at least 1, but " f"is: {adapter_count}") - elif adapter_count > len(all_adapters): + + if adapter_count > len(all_adapters): raise ParameterError( "The 'adapter_count' parameter must not exceed the " f"number of {len(all_adapters)} crypto adapters of type " @@ -989,6 +990,7 @@ def ensure_detached(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return facts about the crypto configuration of the partition. @@ -1043,6 +1045,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -1074,7 +1077,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_hba.py b/plugins/modules/zhmc_hba.py index a2f957a23..8fb39dfeb 100644 --- a/plugins/modules/zhmc_hba.py +++ b/plugins/modules/zhmc_hba.py @@ -248,7 +248,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -376,6 +376,7 @@ def process_properties(partition, hba, params): f"Property {prop_name!r} is not defined in the data model for " "HBAs.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast = \ ZHMC_HBA_PROPERTIES[prop_name] @@ -587,6 +588,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -611,7 +613,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_ldap_server_definition.py b/plugins/modules/zhmc_ldap_server_definition.py index 010f14ec4..44218a097 100644 --- a/plugins/modules/zhmc_ldap_server_definition.py +++ b/plugins/modules/zhmc_ldap_server_definition.py @@ -245,7 +245,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -263,6 +263,7 @@ def casefold(txt): + """Type cast function to casefolded text""" try: return txt.casefold() except AttributeError: @@ -323,7 +324,7 @@ def casefold(txt): } -def process_properties(console, lsd, params): +def process_properties(lsd, params): """ Process the properties specified in the 'properties' module parameter, and return two dictionaries (create_props, update_props) that contain @@ -383,6 +384,7 @@ def process_properties(console, lsd, params): f"Property {prop_name!r} is not defined in the data model for " "LDAP Server Definitions.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast = \ ZHMC_LSD_PROPERTIES[prop_name] @@ -490,8 +492,7 @@ def ensure_present(params, check_mode): if lsd is None: # It does not exist. Create it and update it if there are # update-only properties. - create_props, update_props = \ - process_properties(console, lsd, params) + create_props, update_props = process_properties(lsd, params) update2_props = {} for name, value in update_props.items(): if name not in create_props: @@ -513,8 +514,7 @@ def ensure_present(params, check_mode): # It exists. Update its properties. lsd.pull_full_properties() result = dict(lsd.properties) - create_props, update_props = \ - process_properties(console, lsd, params) + create_props, update_props = process_properties(lsd, params) if create_props: raise AssertionError("Unexpected " "create_props: %r" % create_props) @@ -579,6 +579,7 @@ def ensure_absent(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return facts about an LDAP Server Definition object. @@ -630,6 +631,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -652,7 +654,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_ldap_server_definition_list.py b/plugins/modules/zhmc_ldap_server_definition_list.py index 1fa6b56aa..359446401 100644 --- a/plugins/modules/zhmc_ldap_server_definition_list.py +++ b/plugins/modules/zhmc_ldap_server_definition_list.py @@ -164,7 +164,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -213,6 +213,7 @@ def perform_list(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -231,7 +232,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_lpar.py b/plugins/modules/zhmc_lpar.py index 899516eb1..85e71ffdf 100644 --- a/plugins/modules/zhmc_lpar.py +++ b/plugins/modules/zhmc_lpar.py @@ -622,7 +622,7 @@ common_fail_on_import_errors, pull_properties, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -781,7 +781,7 @@ } -def process_properties(cpc, lpar, params): +def process_properties(lpar, params): """ Process the properties specified in the 'properties' module parameter, and return a dictionarys (update_props) that contains the properties that @@ -832,6 +832,7 @@ def process_properties(cpc, lpar, params): f"Property {prop_name!r} is not defined in the data model for " "LPARs.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast = \ ZHMC_LPAR_PROPERTIES[prop_name] @@ -840,14 +841,13 @@ def process_properties(cpc, lpar, params): f"Property {prop_name!r} is not allowed in the 'properties' " "module parameter.") - else: - # Process a normal (= non-artificial) property - _create_props, _update_props, _stop = process_normal_property( - prop_name, ZHMC_LPAR_PROPERTIES, input_props, lpar) - create_props.update(_create_props) - update_props.update(_update_props) - if _stop: - stop = True + # Process a normal (= non-artificial) property + _create_props, _update_props, _stop = process_normal_property( + prop_name, ZHMC_LPAR_PROPERTIES, input_props, lpar) + create_props.update(_create_props) + update_props.update(_update_props) + if _stop: + stop = True if create_props: raise AssertionError( @@ -861,6 +861,7 @@ def process_properties(cpc, lpar, params): def add_artificial_properties(lpar_properties, lpar): + # pylint: disable=unused-argument """ Add artificial properties to the lpar_properties dict. @@ -872,7 +873,7 @@ def add_artificial_properties(lpar_properties, lpar): pass -def update_lpar_properties(cpc, lpar, params, check_mode, check_status=False): +def update_lpar_properties(lpar, params, check_mode, check_status=False): """ Update the properties of the LPAR on the HMC. @@ -889,7 +890,7 @@ def update_lpar_properties(cpc, lpar, params, check_mode, check_status=False): pull_properties(lpar, select_prop_names, input_prop_names) lpar_properties = dict(lpar.properties) - update_props = process_properties(cpc, lpar, params) + update_props = process_properties(lpar, params) if update_props: if not check_mode: @@ -1087,7 +1088,7 @@ def ensure_active(params, check_mode): # Update the properties of the LPAR. _changed, lpar_properties = update_lpar_properties( - cpc, lpar, params, check_mode) + lpar, params, check_mode) changed |= _changed add_artificial_properties(lpar_properties, lpar) @@ -1146,7 +1147,7 @@ def ensure_loaded(params, check_mode): # Update the properties of the LPAR. _changed, lpar_properties = update_lpar_properties( - cpc, lpar, params, check_mode) + lpar, params, check_mode) changed |= _changed add_artificial_properties(lpar_properties, lpar) @@ -1186,7 +1187,7 @@ def ensure_set(params, check_mode): # Update the properties of the LPAR. _changed, lpar_properties = update_lpar_properties( - cpc, lpar, params, check_mode, check_status=True) + lpar, params, check_mode, check_status=True) changed |= _changed add_artificial_properties(lpar_properties, lpar) @@ -1198,6 +1199,7 @@ def ensure_set(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return LPAR facts. @@ -1263,6 +1265,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -1306,7 +1309,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_lpar_list.py b/plugins/modules/zhmc_lpar_list.py index 7d63df17f..4e30bb83e 100644 --- a/plugins/modules/zhmc_lpar_list.py +++ b/plugins/modules/zhmc_lpar_list.py @@ -239,7 +239,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -385,6 +385,7 @@ def perform_list(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -407,7 +408,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_lpar_messages.py b/plugins/modules/zhmc_lpar_messages.py index 2c0333d0d..446f599f9 100644 --- a/plugins/modules/zhmc_lpar_messages.py +++ b/plugins/modules/zhmc_lpar_messages.py @@ -288,7 +288,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -404,6 +404,7 @@ def perform_os_messages(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -429,7 +430,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_nic.py b/plugins/modules/zhmc_nic.py index bb8046238..0c90c7d11 100644 --- a/plugins/modules/zhmc_nic.py +++ b/plugins/modules/zhmc_nic.py @@ -281,7 +281,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -428,6 +428,7 @@ def process_properties(partition, nic, params): f"Property {prop_name!r} is not defined in the data model for " "NICs.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast = \ ZHMC_NIC_PROPERTIES[prop_name] @@ -657,6 +658,7 @@ def ensure_absent(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return NIC facts. @@ -712,6 +714,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -736,7 +739,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_nic_list.py b/plugins/modules/zhmc_nic_list.py index 33edc22e8..83436823b 100644 --- a/plugins/modules/zhmc_nic_list.py +++ b/plugins/modules/zhmc_nic_list.py @@ -198,7 +198,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -266,6 +266,7 @@ def perform_list(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -287,7 +288,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_partition.py b/plugins/modules/zhmc_partition.py index 0d633145e..1a51eec02 100644 --- a/plugins/modules/zhmc_partition.py +++ b/plugins/modules/zhmc_partition.py @@ -604,8 +604,8 @@ import uuid import random import types -from ansible.module_utils.basic import AnsibleModule # noqa: E402 from operator import itemgetter # noqa: E402 +from ansible.module_utils.basic import AnsibleModule # noqa: E402 from ..module_utils.common import log_init, open_session, close_session, \ hmc_auth_parameter, Error, ParameterError, StatusError, stop_partition, \ @@ -614,7 +614,7 @@ common_fail_on_import_errors, pull_properties, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -1111,6 +1111,7 @@ def process_properties(cpc, partition, params): f"Property {prop_name!r} is not defined in the data model for " "partitions.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast, \ required, default = ZHMC_PARTITION_PROPERTIES[prop_name] @@ -1680,9 +1681,8 @@ def create_check_mode_partition(cpc, create_props, update_props): missing_props = [] # Handle direct requiredness, direct defaults specified in prop defs - for prop_name in ZHMC_PARTITION_PROPERTIES: + for prop_name, prop_defs in ZHMC_PARTITION_PROPERTIES.items(): prop_hmc_name = prop_name.replace('_', '-') - prop_defs = ZHMC_PARTITION_PROPERTIES[prop_name] required = prop_defs[6] default = prop_defs[7] @@ -1722,9 +1722,8 @@ def create_check_mode_partition(cpc, create_props, update_props): input_props['short-name'] = f'{name}{rand_num:04X}' # noqa: E231 # Handle function-based requiredness specified in prop defs - for prop_name in ZHMC_PARTITION_PROPERTIES: + for prop_name, prop_defs in ZHMC_PARTITION_PROPERTIES.items(): prop_hmc_name = prop_name.replace('_', '-') - prop_defs = ZHMC_PARTITION_PROPERTIES[prop_name] required = prop_defs[6] if isinstance(required, types.FunctionType): @@ -1904,6 +1903,7 @@ def ensure_stopped(params, check_mode): if not partition: # It does not exist. Create it and update it if there are # update-only properties. + # pylint: disable=unused-variable create_props, update_props, stop, crypto_changes = \ process_properties(cpc, partition, params) update2_props = {} @@ -2109,6 +2109,7 @@ def ensure_iso_unmount(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return partition facts. @@ -2170,6 +2171,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -2202,7 +2204,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_partition_list.py b/plugins/modules/zhmc_partition_list.py index 96b61a4c7..1539021c6 100644 --- a/plugins/modules/zhmc_partition_list.py +++ b/plugins/modules/zhmc_partition_list.py @@ -236,7 +236,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -378,6 +378,7 @@ def perform_list(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -400,7 +401,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_partition_messages.py b/plugins/modules/zhmc_partition_messages.py index 59c7e926c..f5bb292a1 100644 --- a/plugins/modules/zhmc_partition_messages.py +++ b/plugins/modules/zhmc_partition_messages.py @@ -263,7 +263,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -372,6 +372,7 @@ def perform_os_messages(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -394,7 +395,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_password_rule.py b/plugins/modules/zhmc_password_rule.py index b0323e582..4a00d5cc2 100644 --- a/plugins/modules/zhmc_password_rule.py +++ b/plugins/modules/zhmc_password_rule.py @@ -265,7 +265,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -336,7 +336,7 @@ } -def process_properties(console, pwrule, params): +def process_properties(pwrule, params): """ Process the properties specified in the 'properties' module parameter, and return two dictionaries (create_props, update_props) that contain @@ -396,6 +396,7 @@ def process_properties(console, pwrule, params): f"Property {prop_name!r} is not defined in the data model for " "password rules.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast = \ ZHMC_PASSWORD_RULE_PROPERTIES[prop_name] @@ -496,8 +497,7 @@ def ensure_present(params, check_mode): if pwrule is None: # It does not exist. Create it and update it if there are # update-only properties. - create_props, update_props = \ - process_properties(console, pwrule, params) + create_props, update_props = process_properties(pwrule, params) update2_props = {} for name, value in update_props.items(): if name not in create_props: @@ -519,8 +519,7 @@ def ensure_present(params, check_mode): # It exists. Update its properties. pwrule.pull_full_properties() result = dict(pwrule.properties) - create_props, update_props = \ - process_properties(console, pwrule, params) + create_props, update_props = process_properties(pwrule, params) if create_props: raise AssertionError("Unexpected " "create_props: %r" % create_props) @@ -584,6 +583,7 @@ def ensure_absent(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return facts about a password rule. @@ -634,6 +634,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -656,7 +657,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_password_rule_list.py b/plugins/modules/zhmc_password_rule_list.py index 51a6f203c..987d58e73 100644 --- a/plugins/modules/zhmc_password_rule_list.py +++ b/plugins/modules/zhmc_password_rule_list.py @@ -178,7 +178,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -232,6 +232,7 @@ def perform_list(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -251,7 +252,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_session.py b/plugins/modules/zhmc_session.py index c889e84a8..1c2bcabdb 100644 --- a/plugins/modules/zhmc_session.py +++ b/plugins/modules/zhmc_session.py @@ -224,7 +224,7 @@ missing_required_lib, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -273,6 +273,7 @@ def perform_action(params): # With session_id None, this creates a client-side Session object # that is ready to log on, but it does not immediately create a new # session on the HMC. + # pylint: disable=unused-variable session, logoff = open_session(params) # The logon creates the new session on the HMC and only after that, @@ -321,6 +322,7 @@ def perform_action(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -340,7 +342,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_storage_group.py b/plugins/modules/zhmc_storage_group.py index ef359e889..4a9a96da4 100644 --- a/plugins/modules/zhmc_storage_group.py +++ b/plugins/modules/zhmc_storage_group.py @@ -582,7 +582,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -732,6 +732,7 @@ def process_properties(cpc, storage_group, params): f"Property {prop_name!r} is not defined in the data model for " "storage groups.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast = \ ZHMC_STORAGE_GROUP_PROPERTIES[prop_name] @@ -979,6 +980,7 @@ def ensure_absent(params, check_mode): def discover(params, check_mode): + # pylint: disable=unused-argument """ Trigger LUN discovery for a FCP storage group and return its current facts. @@ -1034,6 +1036,7 @@ def discover(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return facts about a storage group and its storage volumes and virtual storage resources. @@ -1098,6 +1101,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -1124,7 +1128,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_storage_group_attachment.py b/plugins/modules/zhmc_storage_group_attachment.py index acfe762fc..8aab06a51 100644 --- a/plugins/modules/zhmc_storage_group_attachment.py +++ b/plugins/modules/zhmc_storage_group_attachment.py @@ -229,7 +229,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -349,6 +349,7 @@ def ensure_detached(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return facts about the attachment of a storage group to a partition. @@ -416,6 +417,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -439,7 +441,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_storage_volume.py b/plugins/modules/zhmc_storage_volume.py index d18871d13..ae63d14f4 100644 --- a/plugins/modules/zhmc_storage_volume.py +++ b/plugins/modules/zhmc_storage_volume.py @@ -280,7 +280,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -352,7 +352,7 @@ } -def process_properties(cpc, storage_group, storage_volume, params): +def process_properties(storage_volume, params): """ Process the properties specified in the 'properties' module parameter, and return two dictionaries (create_props, update_props) that contain @@ -371,12 +371,6 @@ def process_properties(cpc, storage_group, storage_volume, params): Parameters: - cpc (zhmcclient.Cpc): CPC associated to the storage group of the target - storage volume. - - storage_group (zhmcclient.StorageGroup): Storage group of the target - storage volume. - storage_volume (zhmcclient.StorageVolume): Target storage volume if it currently exists, or `None` if it does not currently exist. @@ -417,6 +411,7 @@ def process_properties(cpc, storage_group, storage_volume, params): f"Property {prop_name!r} is not defined in the data model for " "storage volumes.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast = \ ZHMC_STORAGE_VOLUME_PROPERTIES[prop_name] @@ -499,8 +494,7 @@ def ensure_present(params, check_mode): # update-only properties. if not check_mode: create_props, update_props = \ - process_properties(cpc, storage_group, storage_volume, - params) + process_properties(storage_volume, params) storage_volume = storage_group.storage_volumes.create( create_props) update2_props = {} @@ -520,7 +514,7 @@ def ensure_present(params, check_mode): # It exists. Update its properties. storage_volume.pull_full_properties() create_props, update_props = \ - process_properties(cpc, storage_group, storage_volume, params) + process_properties(storage_volume, params) if create_props: raise AssertionError("Unexpected " "create_props: %r" % create_props) @@ -601,6 +595,7 @@ def ensure_absent(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return facts about a storage volume. @@ -670,6 +665,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -694,7 +690,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_user.py b/plugins/modules/zhmc_user.py index 7ba5988dd..c846ec075 100644 --- a/plugins/modules/zhmc_user.py +++ b/plugins/modules/zhmc_user.py @@ -382,7 +382,7 @@ common_fail_on_import_errors, parse_hmc_host, BLANKED_OUT # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -555,6 +555,7 @@ def process_properties(console, user, params): f"Property {prop_name!r} is not defined in the data model for " "users.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast = \ ZHMC_USER_PROPERTIES[prop_name] @@ -674,8 +675,7 @@ def process_properties(console, user, params): return create_props, update_props, add_roles, rem_roles -def add_artificial_properties( - user_properties, console, user, expand, check_mode): +def add_artificial_properties(user_properties, console, user, expand): """ Add artificial properties to the user_properties dict. @@ -1026,7 +1026,7 @@ def ensure_present(params, check_mode): if not user: raise AssertionError() - add_artificial_properties(result, console, user, expand, check_mode) + add_artificial_properties(result, console, user, expand) if 'password' in result: # This is not a hard-coded password. Added # nosec to avoid @@ -1075,6 +1075,7 @@ def ensure_absent(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return facts about a user. @@ -1099,7 +1100,7 @@ def facts(params, check_mode): user.pull_full_properties() result = dict(user.properties) - add_artificial_properties(result, console, user, expand, check_mode) + add_artificial_properties(result, console, user, expand) return changed, result @@ -1128,6 +1129,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -1151,7 +1153,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_user_list.py b/plugins/modules/zhmc_user_list.py index 9a19a4e76..da1ffb8a8 100644 --- a/plugins/modules/zhmc_user_list.py +++ b/plugins/modules/zhmc_user_list.py @@ -183,7 +183,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -237,6 +237,7 @@ def perform_list(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -256,7 +257,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_user_role.py b/plugins/modules/zhmc_user_role.py index b4ed773bc..b7dbf21ed 100644 --- a/plugins/modules/zhmc_user_role.py +++ b/plugins/modules/zhmc_user_role.py @@ -454,7 +454,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -586,6 +586,7 @@ def process_properties(client, urole, params): f"Property {prop_name!r} is not defined in the data model for " "user roles.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast = \ ZHMC_USER_ROLE_PROPERTIES[prop_name] @@ -615,14 +616,14 @@ def process_properties(client, urole, params): tgt_perms = target_perm_dict(client, input_props[prop_name]) # Mark missing permissions as to be added - for perm_key in tgt_perms: + for perm_key, tgt_perm in tgt_perms.items(): if perm_key not in cur_perms: - add_perms[perm_key] = tgt_perms[perm_key] + add_perms[perm_key] = tgt_perm # Mark superfluous permissions as to be removed - for perm_key in cur_perms: + for perm_key, cur_perm in cur_perms.items(): if perm_key not in tgt_perms: - rem_perms[perm_key] = cur_perms[perm_key] + rem_perms[perm_key] = cur_perm continue @@ -1088,8 +1089,8 @@ def ensure_present(params, check_mode): result = dict(urole.properties) changed = True - for perm_key in rem_perms: - opt_kwargs, obj = rem_perms[perm_key] + for perm_key, rem_perm in rem_perms.items(): + opt_kwargs, obj = rem_perm if obj is None: # resource class kwargs = dict(permitted_object=perm_key) else: @@ -1101,8 +1102,8 @@ def ensure_present(params, check_mode): if not check_mode: urole.remove_permission(**kwargs) del cur_perms[perm_key] - for perm_key in add_perms: - opt_kwargs, obj = add_perms[perm_key] + for perm_key, add_perm in add_perms.items(): + opt_kwargs, obj = add_perm if obj is None: # resource class kwargs = dict(permitted_object=perm_key) else: @@ -1136,8 +1137,8 @@ def ensure_present(params, check_mode): result.update(update_props) changed = True - for perm_key in rem_perms: - opt_kwargs, obj = rem_perms[perm_key] + for perm_key, rem_perm in rem_perms.items(): + opt_kwargs, obj = rem_perm if obj is None: # resource class kwargs = dict(permitted_object=perm_key) else: @@ -1149,8 +1150,8 @@ def ensure_present(params, check_mode): if not check_mode: urole.remove_permission(**kwargs) del cur_perms[perm_key] - for perm_key in add_perms: - opt_kwargs, obj = add_perms[perm_key] + for perm_key, add_perm in add_perms.items(): + opt_kwargs, obj = add_perm if obj is None: # resource class kwargs = dict(permitted_object=perm_key) else: @@ -1219,6 +1220,7 @@ def ensure_absent(params, check_mode): def facts(params, check_mode): + # pylint: disable=unused-argument """ Return facts about a user role. @@ -1282,6 +1284,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -1304,7 +1307,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_user_role_list.py b/plugins/modules/zhmc_user_role_list.py index 97309ba86..3992c57eb 100644 --- a/plugins/modules/zhmc_user_role_list.py +++ b/plugins/modules/zhmc_user_role_list.py @@ -183,7 +183,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -237,6 +237,7 @@ def perform_list(params): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -256,7 +257,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_versions.py b/plugins/modules/zhmc_versions.py index 2167d27dd..c33171194 100644 --- a/plugins/modules/zhmc_versions.py +++ b/plugins/modules/zhmc_versions.py @@ -247,7 +247,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -333,6 +333,7 @@ def get_versions(module): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -353,7 +354,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/plugins/modules/zhmc_virtual_function.py b/plugins/modules/zhmc_virtual_function.py index 1308432f0..19b467d6e 100644 --- a/plugins/modules/zhmc_virtual_function.py +++ b/plugins/modules/zhmc_virtual_function.py @@ -243,7 +243,7 @@ common_fail_on_import_errors, parse_hmc_host # noqa: E402 try: - import requests.packages.urllib3 + import urllib3 IMP_URLLIB3_ERR = None except ImportError: IMP_URLLIB3_ERR = traceback.format_exc() @@ -367,6 +367,7 @@ def process_properties(partition, vfunction, params): f"Property {prop_name!r} is not defined in the data model for " "virtual functions.") + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, type_cast = \ ZHMC_VFUNCTION_PROPERTIES[prop_name] @@ -565,6 +566,7 @@ def perform_task(params, check_mode): def main(): + """Main function""" # The following definition of module input parameters must match the # description of the options in the DOCUMENTATION string. @@ -589,7 +591,7 @@ def main(): module.fail_json(msg=missing_required_lib("requests"), exception=IMP_URLLIB3_ERR) - requests.packages.urllib3.disable_warnings() + urllib3.disable_warnings() if IMP_ZHMCCLIENT_ERR is not None: module.fail_json(msg=missing_required_lib("zhmcclient"), diff --git a/tests/end2end/test_zhmc_adapter.py b/tests/end2end/test_zhmc_adapter.py index 087c7d59c..6782b161b 100644 --- a/tests/end2end/test_zhmc_adapter.py +++ b/tests/end2end/test_zhmc_adapter.py @@ -21,12 +21,12 @@ import uuid import copy -import pytest from unittest import mock import re import random from pprint import pformat -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -36,7 +36,7 @@ from plugins.modules import zhmc_adapter from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() DEBUG = False # Print debug messages DEBUG_LOG = False # Write log file @@ -283,6 +283,7 @@ def assert_adapter_props(act_props, exp_props, hmc_version_info, where): def test_zhmc_adapter_facts( ansible_mod_cls, adapter_family, check_mode, dpm_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_adapter module with state=facts on DPM mode CPCs. """ @@ -391,8 +392,8 @@ def test_zhmc_adapter_facts( } HIPERSOCKET_UPDATE1_EXP_PROPS_HMC = dict(STD_HIPERSOCKET_EXP_PROPS_HMC) for pname, pvalue in HIPERSOCKET_UPDATE1_INPUT_PROPS.items(): - pname_hmc = pname.replace('_', '-') - HIPERSOCKET_UPDATE1_EXP_PROPS_HMC[pname_hmc] = pvalue + _PNAME_HMC = pname.replace('_', '-') + HIPERSOCKET_UPDATE1_EXP_PROPS_HMC[_PNAME_HMC] = pvalue ADAPTER_STATES_TESTCASES = [ # The list items are tuples with the following items: @@ -580,6 +581,7 @@ def test_zhmc_adapter_states( desc, initial_props, input_state, input_name, input_match, input_props, exp_props, exp_changed, exp_msg_pattern, check_mode, dpm_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_adapter module with state=absent/present on DPM mode CPCs, with Hipersocket adapters. diff --git a/tests/end2end/test_zhmc_adapter_list.py b/tests/end2end/test_zhmc_adapter_list.py index 6e6bad445..e9d8f447f 100644 --- a/tests/end2end/test_zhmc_adapter_list.py +++ b/tests/end2end/test_zhmc_adapter_list.py @@ -19,9 +19,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -31,7 +31,7 @@ from plugins.modules import zhmc_adapter_list from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -141,6 +141,7 @@ def assert_adapter_list(adapter_list, exp_adapter_dict): def test_zhmc_adapter_list( ansible_mod_cls, check_mode, property_flags, filters, with_cpc, dpm_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_adapter_list module with DPM mode CPCs. """ @@ -247,8 +248,7 @@ def test_zhmc_adapter_list( all_adapters = cpc.adapters.list() all_adapter_ids = [ad.properties['adapter-id'] for ad in all_adapters].sort() - exp_adapter_ids = \ - [item[1] for item in exp_adapter_dict.keys()].sort() + exp_adapter_ids = [item[1] for item in exp_adapter_dict].sort() assert exp_adapter_ids == all_adapter_ids, \ "cpc.adapters.list() with 'name' filter does not seem to " \ "support regular expressions" diff --git a/tests/end2end/test_zhmc_cpc.py b/tests/end2end/test_zhmc_cpc.py index a1f3a01c0..936db9d45 100644 --- a/tests/end2end/test_zhmc_cpc.py +++ b/tests/end2end/test_zhmc_cpc.py @@ -19,9 +19,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 from zhmcclient.testutils import all_cpcs # noqa: F401, E501 @@ -31,7 +31,7 @@ from .utils import mock_ansible_module, get_failure_msg, setup_logging, \ skip_warn -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() DEBUG = False # Print debug messages @@ -186,6 +186,7 @@ def test_zhmc_cpc_facts( desc, select_properties, exp_prop_names, not_prop_names, exp_msg, exp_changed, run, check_mode, all_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_cpc module with state=facts on any CPCs. """ diff --git a/tests/end2end/test_zhmc_cpc_list.py b/tests/end2end/test_zhmc_cpc_list.py index e83a3814e..48774e46d 100644 --- a/tests/end2end/test_zhmc_cpc_list.py +++ b/tests/end2end/test_zhmc_cpc_list.py @@ -19,9 +19,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -30,7 +30,7 @@ from plugins.modules import zhmc_cpc_list from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -174,6 +174,7 @@ def assert_cpc_list( def test_zhmc_cpc_list( ansible_mod_cls, check_mode, include_unmanaged_cpcs, property_flags, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_cpc_list module with managed and unmanaged CPCs. """ diff --git a/tests/end2end/test_zhmc_ldap_server_definition.py b/tests/end2end/test_zhmc_ldap_server_definition.py index 5785cc9cf..6b883a978 100644 --- a/tests/end2end/test_zhmc_ldap_server_definition.py +++ b/tests/end2end/test_zhmc_ldap_server_definition.py @@ -20,11 +20,11 @@ __metaclass__ = type import uuid -import pytest from unittest import mock import random from pprint import pformat -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -33,7 +33,7 @@ from plugins.modules import zhmc_ldap_server_definition from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -69,13 +69,8 @@ } -def updated_copy(dict1, dict2): - dict1c = dict1.copy() - dict1c.update(dict2) - return dict1c - - def new_lsd_name(): + """Return random unique LSD name""" lsd_name = f'test_{uuid.uuid4()}' return lsd_name @@ -155,9 +150,10 @@ def assert_lsd_props(lsd_props, exp_lsd_props, where): ) @mock.patch("plugins.modules.zhmc_ldap_server_definition.AnsibleModule", autospec=True) -def test_zhmc_ldap_server_definition_facts( +def test_zhmc_lsd_facts( ansible_mod_cls, check_mode, diff_case, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_ldap_server_definition module with state=facts. """ @@ -286,12 +282,13 @@ def test_zhmc_ldap_server_definition_facts( LSD_ABSENT_PRESENT_TESTCASES) @mock.patch("plugins.modules.zhmc_ldap_server_definition.AnsibleModule", autospec=True) -def test_zhmc_ldap_server_definition_absent_present( +def test_zhmc_lsd_absent_present( ansible_mod_cls, desc, initial_lsd_props, input_state, input_props, exp_lsd_props, exp_changed, check_mode, diff_case, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_ldap_server_definition module with state=absent/present. """ diff --git a/tests/end2end/test_zhmc_ldap_server_definition_list.py b/tests/end2end/test_zhmc_ldap_server_definition_list.py index f4a048580..3c71e46d5 100644 --- a/tests/end2end/test_zhmc_ldap_server_definition_list.py +++ b/tests/end2end/test_zhmc_ldap_server_definition_list.py @@ -19,9 +19,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -30,7 +30,7 @@ from plugins.modules import zhmc_ldap_server_definition_list from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -91,6 +91,7 @@ def assert_lsd_list(lsd_list, exp_lsd_dict): autospec=True) def test_zhmc_ldap_server_definition_list( ansible_mod_cls, check_mode, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_ldap_server_definition_list module. """ diff --git a/tests/end2end/test_zhmc_lpar.py b/tests/end2end/test_zhmc_lpar.py index 6222d47b0..53b18adb4 100644 --- a/tests/end2end/test_zhmc_lpar.py +++ b/tests/end2end/test_zhmc_lpar.py @@ -22,10 +22,9 @@ import random import pdb import re - -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -39,7 +38,7 @@ setup_logging, set_resource_property -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages in tests DEBUG = False @@ -577,7 +576,7 @@ def test_zhmc_lpar_state( run, check_mode, classic_mode_cpcs): # noqa: F811, E501 - # pylint: disable=redefined-outer-name, unused-argument + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_lpar module with different initial and target state. @@ -667,6 +666,7 @@ def test_zhmc_lpar_state( if len(lpar_iaps) >= 1: iap = lpar_iaps[0] else: + iap = None # avoid pylint possibly-used-before-assignment pytest.skip(f"Image activation profile {iap_name!r} does not " f"exist on CPC {cpc.name}.") wrong_iap_names = [_iap.name for _iap in all_iaps @@ -726,7 +726,7 @@ def test_zhmc_lpar_state( logger.info(msg) if run == 'pdb': - pdb.set_trace() + pdb.set_trace() # pylint: disable=forgotten-debug-statement logger.info("Preparation: Ensuring that LPAR %r has status %r", lpar.name, initial_status) @@ -956,7 +956,7 @@ def test_zhmc_lpar_facts( desc, select_properties, exp_prop_names, not_prop_names, exp_msg, exp_changed, run, check_mode, classic_mode_cpcs): # noqa: F811, E501 - # pylint: disable=redefined-outer-name, unused-argument + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_lpar module with state=facts. @@ -992,7 +992,7 @@ def test_zhmc_lpar_facts( logger.info(msg) if run == 'pdb': - pdb.set_trace() + pdb.set_trace() # pylint: disable=forgotten-debug-statement # Prepare module input parameters (must be all required + optional) params = { diff --git a/tests/end2end/test_zhmc_lpar_list.py b/tests/end2end/test_zhmc_lpar_list.py index 3839edd62..8b90b1799 100644 --- a/tests/end2end/test_zhmc_lpar_list.py +++ b/tests/end2end/test_zhmc_lpar_list.py @@ -19,9 +19,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -31,7 +31,7 @@ from plugins.modules import zhmc_lpar_list from .utils import mock_ansible_module, get_failure_msg, setup_logging -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Create log file LOGGING = False @@ -148,6 +148,7 @@ def assert_lpar_list(lpar_list, exp_lpar_dict): def test_zhmc_lpar_list( ansible_mod_cls, check_mode, property_flags, with_cpc, classic_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_lpar_list module with classic mode CPCs. """ diff --git a/tests/end2end/test_zhmc_lpar_messages.py b/tests/end2end/test_zhmc_lpar_messages.py index 87220719b..3a1c37b40 100644 --- a/tests/end2end/test_zhmc_lpar_messages.py +++ b/tests/end2end/test_zhmc_lpar_messages.py @@ -20,9 +20,9 @@ __metaclass__ = type import random -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 from zhmcclient.testutils import classic_mode_cpcs # noqa: F401, E501 @@ -31,7 +31,7 @@ from plugins.modules import zhmc_lpar_messages from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() LOGGING = False LOG_FILE = 'zhmc_lpar_messages.log' if LOGGING else None @@ -137,6 +137,7 @@ def test_zhmc_lpar_messages( ansible_mod_cls, check_mode, desc, in_params, exp_seqnos, classic_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_lpar_messages module with classic mode CPCs. """ diff --git a/tests/end2end/test_zhmc_partition.py b/tests/end2end/test_zhmc_partition.py index e8b8cc93f..f6568dea1 100644 --- a/tests/end2end/test_zhmc_partition.py +++ b/tests/end2end/test_zhmc_partition.py @@ -21,13 +21,13 @@ import uuid import copy -import pytest from unittest import mock import re import random import pdb from pprint import pformat -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -39,7 +39,7 @@ from .utils import mock_ansible_module, get_failure_msg, setup_logging, \ skip_warn -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() DEBUG = False # Print debug messages @@ -210,9 +210,8 @@ def setup_partition(hd, cpc, name, properties, status='stopped'): f"{name!r} into status 'starting'") try: partition.start(wait_for_completion=False) - except zhmcclient.Error as exc: - if isinstance(exc, zhmcclient.HTTPError) \ - and exc.http_status == 409 and exc.reason == 131: + except zhmcclient.HTTPError as exc: + if exc.http_status == 409 and exc.reason == 131: # SSC partitions boot the built-in installer. However, # there seems to be an issue where the SSC partition fails # to start with "HTTPError: 409,131: The operating system in @@ -224,6 +223,10 @@ def setup_partition(hd, cpc, name, properties, status='stopped'): raise AssertionError( "Starting test partition without waiting for " f"completion failed with: {exc}") + except zhmcclient.Error as exc: + raise AssertionError( + "Starting test partition without waiting for " + f"completion failed with: {exc}") current_status = pull_partition_status(partition) if current_status != 'starting': raise AssertionError( @@ -272,9 +275,8 @@ def setup_partition(hd, cpc, name, properties, status='stopped'): try: job = partition.start(wait_for_completion=False) job.wait_for_completion() - except zhmcclient.Error as exc: - if isinstance(exc, zhmcclient.HTTPError) \ - and exc.http_status == 409 and exc.reason == 131: + except zhmcclient.HTTPError as exc: + if exc.http_status == 409 and exc.reason == 131: # SSC partitions boot the built-in installer. However, # there seems to be an issue where the SSC partition fails # to start with "HTTPError: 409,131: The operating system in @@ -287,6 +289,11 @@ def setup_partition(hd, cpc, name, properties, status='stopped'): "setup_partition: Starting SSC test partition " f"{name!r} and waiting for completion failed with: " f"{exc}") + except zhmcclient.Error as exc: + raise AssertionError( + "setup_partition: Starting SSC test partition " + f"{name!r} and waiting for completion failed with: " + f"{exc}") current_status = pull_partition_status(partition) if current_status != 'active': raise AssertionError( @@ -329,14 +336,14 @@ def setup_partition(hd, cpc, name, properties, status='stopped'): f"{name!r}.") except zhmcclient.Error as exc: - teardown_partition(hd, cpc, name) + teardown_partition(cpc, name) pytest.skip("Error in HMC operation during test partition setup: " f"{exc}") return partition -def teardown_partition(hd, cpc, name): +def teardown_partition(cpc, name): """ Delete a partition created for test purposes by setup_partition(). @@ -347,7 +354,6 @@ def teardown_partition(hd, cpc, name): deleted. Parameters: - hd(zhmcclient.testutils.HMCDefinition): HMC definition context. cpc(zhmcclient.Cpc): CPC on which the partition has been created. name(string): Partition name. """ @@ -623,6 +629,7 @@ def test_zhmc_partition_facts( desc, select_properties, exp_prop_names, not_prop_names, exp_msg, exp_changed, run, check_mode, dpm_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_partition module with state=facts on DPM mode CPCs. """ @@ -893,6 +900,7 @@ def test_zhmc_partition_state( desc, initial_props, initial_status, input_state, input_props, exp_msg, exp_props, exp_changed, run, check_mode, dpm_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_partition module with different initial and target state. """ @@ -960,7 +968,7 @@ def test_zhmc_partition_state( with pytest.raises(SystemExit) as exc_info: if run == 'pdb': - pdb.set_trace() + pdb.set_trace() # pylint: disable=forgotten-debug-statement # Exercise the code to be tested zhmc_partition.main() @@ -1015,7 +1023,7 @@ def test_zhmc_partition_state( assert_partition_props(output_props, exp_props, where) finally: - teardown_partition(hd, cpc, partition_name) + teardown_partition(cpc, partition_name) # New values for updating properties. @@ -1192,6 +1200,7 @@ def test_zhmc_partition_state( @mock.patch("plugins.modules.zhmc_partition.AnsibleModule", autospec=True) def test_zhmc_partition_properties( ansible_mod_cls, type_state, check_mode, dpm_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_partition module with updating properties. """ @@ -1299,6 +1308,7 @@ def test_zhmc_partition_properties( else: new_value = value_item new_hmc_value = value_item + # pylint: disable=unused-variable allowed, create, update, update_while_active, eq_func, \ type_cast, required, default = \ zhmc_partition.ZHMC_PARTITION_PROPERTIES[prop_name] @@ -1415,7 +1425,7 @@ def test_zhmc_partition_properties( assert_partition_props(output_props, exp_props, where) finally: - teardown_partition(hd, cpc, partition_name) + teardown_partition(cpc, partition_name) @pytest.mark.parametrize( @@ -1438,6 +1448,7 @@ def test_zhmc_partition_properties( @mock.patch("plugins.modules.zhmc_partition.AnsibleModule", autospec=True) def test_zhmc_partition_boot_stovol( ansible_mod_cls, type_state, via, check_mode, dpm_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_partition module when configuring boot from a storage volume. """ @@ -1576,7 +1587,7 @@ def test_zhmc_partition_boot_stovol( if stogrp: partition.detach_storage_group(stogrp) stogrp.delete() - teardown_partition(hd, cpc, partition_name) + teardown_partition(cpc, partition_name) PARTITION_ISO_MOUNT_TESTCASES = [ @@ -1639,6 +1650,7 @@ def test_zhmc_partition_iso_mount( ansible_mod_cls, desc, image_name, image_file, ins_file, exp_msg, exp_changed, check_mode, dpm_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_partition module with state='iso_mount'. """ @@ -1719,7 +1731,7 @@ def test_zhmc_partition_iso_mount( image_name = partition.get_property('boot-iso-image-name') if image_name: partition.unmount_iso_image() - teardown_partition(hd, cpc, partition_name) + teardown_partition(cpc, partition_name) # TODO: Testcases for ISO unmount diff --git a/tests/end2end/test_zhmc_partition_list.py b/tests/end2end/test_zhmc_partition_list.py index ac3a4d581..2873015fc 100644 --- a/tests/end2end/test_zhmc_partition_list.py +++ b/tests/end2end/test_zhmc_partition_list.py @@ -19,9 +19,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -31,7 +31,7 @@ from plugins.modules import zhmc_partition_list from .utils import mock_ansible_module, get_failure_msg, setup_logging -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Create log file LOGGING = False @@ -138,6 +138,7 @@ def assert_partition_list(partition_list, exp_partition_dict): def test_zhmc_partition_list( ansible_mod_cls, check_mode, property_flags, with_cpc, dpm_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_partition_list module with DPM mode CPCs. """ diff --git a/tests/end2end/test_zhmc_partition_messages.py b/tests/end2end/test_zhmc_partition_messages.py index a1672efd2..a7b109892 100644 --- a/tests/end2end/test_zhmc_partition_messages.py +++ b/tests/end2end/test_zhmc_partition_messages.py @@ -20,9 +20,9 @@ __metaclass__ = type import random -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 from zhmcclient.testutils import dpm_mode_cpcs # noqa: F401, E501 @@ -31,7 +31,7 @@ from plugins.modules import zhmc_partition_messages from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() LOGGING = False LOG_FILE = 'zhmc_partition_messages.log' if LOGGING else None @@ -90,6 +90,7 @@ def test_zhmc_partition_messages( ansible_mod_cls, check_mode, desc, in_params, exp_seqnos, dpm_mode_cpcs): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_partition_messages module with DPM mode CPCs. """ diff --git a/tests/end2end/test_zhmc_password_rule.py b/tests/end2end/test_zhmc_password_rule.py index e9ff0f70e..a7fdb6346 100644 --- a/tests/end2end/test_zhmc_password_rule.py +++ b/tests/end2end/test_zhmc_password_rule.py @@ -20,12 +20,12 @@ __metaclass__ = type import uuid -import pytest from unittest import mock import random -import requests.packages.urllib3 from collections import OrderedDict from pprint import pformat +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -34,7 +34,7 @@ from plugins.modules import zhmc_password_rule from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -81,13 +81,8 @@ } -def updated_copy(dict1, dict2): - dict1c = dict1.copy() - dict1c.update(dict2) - return dict1c - - def new_pwrule_name(): + """Return random unique passsword rule name""" pwrule_name = f'test_{uuid.uuid4()}' return pwrule_name @@ -134,6 +129,7 @@ def assert_pwrule_props(pwrule_props, where): @mock.patch("plugins.modules.zhmc_password_rule.AnsibleModule", autospec=True) def test_zhmc_password_rule_facts( ansible_mod_cls, check_mode, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_password_rule module with state=facts. """ @@ -258,6 +254,7 @@ def test_zhmc_password_rule_absent_present( input_props, exp_pwrule_props, exp_changed, check_mode, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_password_rule module with state=absent/present. """ diff --git a/tests/end2end/test_zhmc_password_rule_list.py b/tests/end2end/test_zhmc_password_rule_list.py index ee767cf09..592e20e58 100644 --- a/tests/end2end/test_zhmc_password_rule_list.py +++ b/tests/end2end/test_zhmc_password_rule_list.py @@ -19,9 +19,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -30,7 +30,7 @@ from plugins.modules import zhmc_password_rule_list from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -121,6 +121,7 @@ def assert_pwrule_list(pwrule_list, exp_pwrule_dict): def test_zhmc_password_rule_list( ansible_mod_cls, check_mode, property_flags, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_password_rule_list module. """ diff --git a/tests/end2end/test_zhmc_session.py b/tests/end2end/test_zhmc_session.py index 62b0e3030..b108c5087 100644 --- a/tests/end2end/test_zhmc_session.py +++ b/tests/end2end/test_zhmc_session.py @@ -20,9 +20,9 @@ __metaclass__ = type import re -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition # noqa: F401, E501 # pylint: enable=line-too-long,unused-import @@ -31,7 +31,7 @@ from plugins.module_utils.common import parse_hmc_host from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -219,6 +219,7 @@ def test_zhmc_session_single( ansible_mod_cls, desc, check_mode, in_params, exp_exit_code, exp_msg_pattern, exp_changed, exp_hmc_auth, hmc_definition): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test specific input parameters on single invocations of the zhmc_session module. @@ -337,6 +338,7 @@ def test_zhmc_session_single( @mock.patch("plugins.modules.zhmc_cpc_list.AnsibleModule", autospec=True) def test_zhmc_session_sequence( cpc_list_mod_cls, session_mod_cls, hmc_definition): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test a sequence of playbook tasks with create, use, delete of sessions with the zhmc_session module. diff --git a/tests/end2end/test_zhmc_user.py b/tests/end2end/test_zhmc_user.py index b26acb30c..0f217e098 100644 --- a/tests/end2end/test_zhmc_user.py +++ b/tests/end2end/test_zhmc_user.py @@ -20,12 +20,12 @@ __metaclass__ = type import uuid -import pytest from unittest import mock import random -import requests.packages.urllib3 from collections import OrderedDict from pprint import pformat +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -34,7 +34,7 @@ from plugins.modules import zhmc_user from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -157,13 +157,8 @@ STD_USER_PROPERTIES_WITH_PW['password'] = "Bumerang9x" -def updated_copy(dict1, dict2): - dict1c = dict1.copy() - dict1c.update(dict2) - return dict1c - - def new_user_name(): + """Return random unique user name""" user_name = f'test_{uuid.uuid4()}' return user_name @@ -253,7 +248,9 @@ def assert_user_props(user_props, expand, where): ) @mock.patch("plugins.modules.zhmc_user.AnsibleModule", autospec=True) def test_zhmc_user_facts( - ansible_mod_cls, user_type, auth_type, expand, check_mode, hmc_session): # noqa: F811, E501 + ansible_mod_cls, user_type, auth_type, expand, check_mode, + hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_user module with state=facts. """ @@ -396,6 +393,7 @@ def test_zhmc_user_absent_present( input_props, exp_user_props, exp_changed, check_mode, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_user module with state=absent/present. """ diff --git a/tests/end2end/test_zhmc_user_list.py b/tests/end2end/test_zhmc_user_list.py index cbc2bbcc1..30bec6a7c 100644 --- a/tests/end2end/test_zhmc_user_list.py +++ b/tests/end2end/test_zhmc_user_list.py @@ -19,9 +19,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -30,7 +30,7 @@ from plugins.modules import zhmc_user_list from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -126,6 +126,7 @@ def assert_user_list(user_list, exp_user_dict): def test_zhmc_user_list( ansible_mod_cls, check_mode, property_flags, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_user_list module. """ diff --git a/tests/end2end/test_zhmc_user_role.py b/tests/end2end/test_zhmc_user_role.py index dcb2a58cd..dc8d64c4c 100644 --- a/tests/end2end/test_zhmc_user_role.py +++ b/tests/end2end/test_zhmc_user_role.py @@ -20,11 +20,11 @@ __metaclass__ = type import uuid -import pytest from unittest import mock import random from pprint import pformat -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -33,7 +33,7 @@ from plugins.modules import zhmc_user_role from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -69,13 +69,8 @@ } -def updated_copy(dict1, dict2): - dict1c = dict1.copy() - dict1c.update(dict2) - return dict1c - - def new_urole_name(): + """Return random unique user role name""" urole_name = f'test_{uuid.uuid4()}' return urole_name @@ -137,6 +132,7 @@ def assert_urole_props(urole_props, exp_urole_props, where): @mock.patch("plugins.modules.zhmc_user_role.AnsibleModule", autospec=True) def test_zhmc_user_role_facts( ansible_mod_cls, check_mode, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_user_role module with state=facts. """ @@ -260,6 +256,7 @@ def test_zhmc_user_role_absent_present( input_props, exp_urole_props, exp_changed, check_mode, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name,unused-argument """ Test the zhmc_user_role module with state=absent/present. """ diff --git a/tests/end2end/test_zhmc_user_role_list.py b/tests/end2end/test_zhmc_user_role_list.py index 604e81bbc..011e4519b 100644 --- a/tests/end2end/test_zhmc_user_role_list.py +++ b/tests/end2end/test_zhmc_user_role_list.py @@ -19,9 +19,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -30,7 +30,7 @@ from plugins.modules import zhmc_user_role_list from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -109,6 +109,7 @@ def assert_urole_list(urole_list, exp_urole_dict): def test_zhmc_user_role_list( ansible_mod_cls, check_mode, property_flags, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_user_role_list module. """ diff --git a/tests/end2end/test_zhmc_versions.py b/tests/end2end/test_zhmc_versions.py index 509957e90..917834f85 100644 --- a/tests/end2end/test_zhmc_versions.py +++ b/tests/end2end/test_zhmc_versions.py @@ -19,9 +19,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock -import requests.packages.urllib3 +import pytest +import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils import hmc_definition, hmc_session # noqa: F401, E501 @@ -30,7 +30,7 @@ from plugins.modules import zhmc_versions from .utils import mock_ansible_module, get_failure_msg -requests.packages.urllib3.disable_warnings() +urllib3.disable_warnings() # Print debug messages DEBUG = False @@ -137,6 +137,7 @@ def assert_versions( def test_zhmc_versions( ansible_mod_cls, cpc_filter, check_mode, hmc_session): # noqa: F811, E501 + # pylint: disable=redefined-outer-name """ Test the zhmc_versions module. """ diff --git a/tests/function/test_func_cpc.py b/tests/function/test_func_cpc.py index 09d401083..7d3797a8a 100644 --- a/tests/function/test_func_cpc.py +++ b/tests/function/test_func_cpc.py @@ -22,9 +22,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock import re +import pytest from zhmcclient import Client from zhmcclient_mock import FakedSession @@ -349,13 +349,16 @@ class TestCpc: All tests for CPCs. """ + def __init__(self): + self.session = None + self.client = None + def setup_method(self): """ Using the zhmcclient mock support, set up a CPC in classic mode. """ self.session = FakedSession(**FAKED_SESSION_KWARGS) self.client = Client(self.session) - self.console = self.session.hmc.consoles.add(FAKED_CONSOLE) @pytest.mark.parametrize( "check_mode", [False, True]) @@ -382,18 +385,18 @@ def test_cpc_state(self, ansible_mod_cls, testcases, check_mode): exp_changed = testcases['exp_changed'] # Create the faked CPC - self.faked_cpc = self.session.hmc.cpcs.add(faked_cpc) + faked_cpc = self.session.hmc.cpcs.add(faked_cpc) cpcs = self.client.cpcs.list() assert len(cpcs) == 1 - self.cpc = cpcs[0] - self.cpc.pull_full_properties() + cpc = cpcs[0] + cpc.pull_full_properties() # Prepare module input parameters (must be all required + optional) params = { 'hmc_host': 'fake-host', 'hmc_auth': dict(userid='fake-userid', password='fake-password'), - 'name': self.cpc.name, + 'name': cpc.name, 'state': input_state, 'select_properties': None, 'activation_profile_name': None, @@ -444,9 +447,9 @@ def test_cpc_state(self, ansible_mod_cls, testcases, check_mode): # Assert the updated CPC resource if input_state in ('active', 'set') and not check_mode: if exp_cpc_properties: - self.cpc.pull_full_properties() + cpc.pull_full_properties() for ansi_name, exp_value in exp_cpc_properties.items(): hmc_name = ansi_name.replace('_', '-') - assert hmc_name in self.cpc.properties - assert exp_value == self.cpc.properties[hmc_name], \ + assert hmc_name in cpc.properties + assert exp_value == cpc.properties[hmc_name], \ f"Unexpected value for property {hmc_name!r}" diff --git a/tests/function/test_func_lpar.py b/tests/function/test_func_lpar.py index 251ddefd0..9dcee7dd7 100644 --- a/tests/function/test_func_lpar.py +++ b/tests/function/test_func_lpar.py @@ -22,8 +22,8 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock +import pytest from zhmcclient import Client from zhmcclient_mock import FakedSession @@ -281,6 +281,16 @@ class TestLpar: All tests for LPARs. """ + def __init__(self): + self.session = None + self.client = None + self.faked_cpc = None + self.cpc = None + self.lpar_name = None + self.faked_lpar = None + self.lpar = None + self.faked_image_profile = None + def setup_method(self): """ Using the zhmcclient mock support, set up a CPC in classic mode, that @@ -288,13 +298,10 @@ def setup_method(self): """ self.session = FakedSession(**FAKED_SESSION_KWARGS) self.client = Client(self.session) - self.console = self.session.hmc.consoles.add(FAKED_CONSOLE) self.faked_cpc = self.session.hmc.cpcs.add(FAKED_CPC_1) cpcs = self.client.cpcs.list() assert len(cpcs) == 1 self.cpc = cpcs[0] - self.faked_crypto_adapters = [] - self.faked_crypto_adapter_names = [] def setup_lpar(self, initial_state, additional_props=None): """ diff --git a/tests/function/test_func_partition.py b/tests/function/test_func_partition.py index c94900f1a..3d4237767 100755 --- a/tests/function/test_func_partition.py +++ b/tests/function/test_func_partition.py @@ -22,9 +22,9 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock import re +import pytest from zhmcclient import Client from zhmcclient_mock import FakedSession @@ -818,6 +818,33 @@ class TestPartition: All tests for partitions. """ + def __init__(self): + self.session = None + self.client = None + self.faked_console = None + self.console = None + self.faked_cpc = None + self.cpc = None + self.faked_crypto_adapters = None + self.faked_crypto_adapter_names = None + self.partition_name = None + self.faked_partition = None + self.partition = None + self.hba_name = None + self.faked_hba = None + self.hba = None + self.sg_name = None + self.faked_sg = None + self.sg = None + self.sv_name = None + self.faked_sv = None + self.sv = None + self.faked_adapter = None + self.faked_vswitch = None + self.nic_name = None + self.faked_nic = None + self.nic = None + def setup_method(self): """ Using the zhmcclient mock support, set up a CPC in DPM mode, that has @@ -1593,6 +1620,7 @@ def test_boot_network_error_hba_not_found( def test_crypto_config_success( self, ansible_mod_cls, desc, adapters, initial_config, input_props, exp_config, exp_changed, desired_state, initial_state, check_mode): + # pylint: disable=unused-argument """ Tests for successful crypto configuration. """ diff --git a/tests/unit/test_common.py b/tests/unit/test_common.py index 5050add50..eaee56858 100644 --- a/tests/unit/test_common.py +++ b/tests/unit/test_common.py @@ -123,6 +123,7 @@ COMMON_PARSE_HMC_HOST_TESTCASES) def test_common_parse_hmc_host( desc, in_hmc_host, exp_hmc_host, exp_exc_type, exp_exc_pattern): + # pylint: disable=unused-argument """ Test the parse_hmc_host() function. """ diff --git a/tests/unit/test_hba.py b/tests/unit/test_hba.py index ed2f33aaa..66d429ec4 100755 --- a/tests/unit/test_hba.py +++ b/tests/unit/test_hba.py @@ -20,242 +20,234 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock +import pytest from plugins.modules import zhmc_hba from plugins.module_utils import common as module_utils -class TestZhmcHbaMain: +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_hba.perform_task", + autospec=True) +@mock.patch("plugins.modules.zhmc_hba.AnsibleModule", + autospec=True) +def test_main_success( + ansible_mod_cls, perform_task_func, check_mode): """ - Unit tests for the main() function. + Test main() with all required module parameters. """ - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_hba.perform_task", - autospec=True) - @mock.patch("plugins.modules.zhmc_hba.AnsibleModule", - autospec=True) - def test_main_success( - self, ansible_mod_cls, perform_task_func, check_mode): - """ - Test main() with all required module parameters. - """ - - # Module invocation - params = { - 'hmc_host': 'fake-host', - 'hmc_auth': dict(userid='fake-userid', - password='fake-password'), - 'cpc_name': 'fake-cpc-name', - 'partition_name': 'fake-partition-name', - 'name': 'fake-hba-name', - 'state': 'absent', - 'log_file': None, - } - - # Return values of perform_task() - perform_task_changed = True - perform_task_result = {} - - # Prepare mocks - mod_obj = ansible_mod_cls.return_value - mod_obj.params = params - mod_obj.check_mode = check_mode - mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) - mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) - perform_task_func.return_value = (perform_task_changed, - perform_task_result) - - # Exercise the code to be tested - with pytest.raises(SystemExit) as exc_info: - zhmc_hba.main() - exit_code = exc_info.value.args[0] - - # Assert module exit code - assert exit_code == 0 - - # Assert call to AnsibleModule() - expected_argument_spec = dict( - hmc_host=dict(required=True, type='raw'), - hmc_auth=dict( - required=True, - type='dict', - options=dict( - userid=dict(required=False, type='str', default=None), - password=dict(required=False, type='str', default=None, - no_log=True), - session_id=dict(required=False, type='str', default=None, - no_log=True), - ca_certs=dict(required=False, type='str', default=None), - verify=dict(required=False, type='bool', default=True), - ), + # Module invocation + params = { + 'hmc_host': 'fake-host', + 'hmc_auth': dict(userid='fake-userid', + password='fake-password'), + 'cpc_name': 'fake-cpc-name', + 'partition_name': 'fake-partition-name', + 'name': 'fake-hba-name', + 'state': 'absent', + 'log_file': None, + } + + # Return values of perform_task() + perform_task_changed = True + perform_task_result = {} + + # Prepare mocks + mod_obj = ansible_mod_cls.return_value + mod_obj.params = params + mod_obj.check_mode = check_mode + mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) + mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) + perform_task_func.return_value = (perform_task_changed, + perform_task_result) + + # Exercise the code to be tested + with pytest.raises(SystemExit) as exc_info: + zhmc_hba.main() + exit_code = exc_info.value.args[0] + + # Assert module exit code + assert exit_code == 0 + + # Assert call to AnsibleModule() + expected_argument_spec = dict( + hmc_host=dict(required=True, type='raw'), + hmc_auth=dict( + required=True, + type='dict', + options=dict( + userid=dict(required=False, type='str', default=None), + password=dict(required=False, type='str', default=None, + no_log=True), + session_id=dict(required=False, type='str', default=None, + no_log=True), + ca_certs=dict(required=False, type='str', default=None), + verify=dict(required=False, type='bool', default=True), ), - cpc_name=dict(required=True, type='str'), - partition_name=dict(required=True, type='str'), - name=dict(required=True, type='str'), - state=dict(required=True, type='str', - choices=['absent', 'present']), - properties=dict(required=False, type='dict', default=None), - log_file=dict(required=False, type='str', default=None), - _faked_session=dict(required=False, type='raw'), - ) - assert ansible_mod_cls.call_args == \ - mock.call(argument_spec=expected_argument_spec, - supports_check_mode=True) - - # Assert call to perform_task() - assert perform_task_func.call_args == mock.call(params, check_mode) - - # Assert call to exit_json() - assert mod_obj.exit_json.call_args == \ - mock.call(changed=perform_task_changed, hba=perform_task_result) - - # Assert no call to fail_json() - assert mod_obj.fail_json.called is False - - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_hba.perform_task", - autospec=True) - @mock.patch("plugins.modules.zhmc_hba.AnsibleModule", - autospec=True) - def test_main_param_error( - self, ansible_mod_cls, perform_task_func, check_mode): - """ - Test main() with ParameterError being raised in perform_task(). - """ - - # Module invocation - params = { - 'hmc_host': 'fake-host', - 'hmc_auth': dict(userid='fake-userid', - password='fake-password'), - 'cpc_name': 'fake-cpc-name', - 'partition_name': 'fake-partition-name', - 'name': 'fake-hba-name', - 'state': 'absent', - 'log_file': None, - } - - # Exception raised by perform_task() - perform_task_exc = module_utils.ParameterError("fake message") - - # Prepare mocks - mod_obj = ansible_mod_cls.return_value - mod_obj.params = params - mod_obj.check_mode = check_mode - mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) - mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) - perform_task_func.mock.configure_mock(side_effect=perform_task_exc) - - # Exercise the code to be tested - with pytest.raises(SystemExit) as exc_info: - zhmc_hba.main() - exit_code = exc_info.value.args[0] - - # Assert module exit code - assert exit_code == 1 - - # Assert call to perform_task() - assert perform_task_func.call_args == mock.call(params, check_mode) - - # Assert call to fail_json() - assert mod_obj.fail_json.call_args == \ - mock.call(msg="ParameterError: fake message") - - # Assert no call to exit_json() - assert mod_obj.exit_json.called is False - - -class TestZhmcHbaPerformTask: + ), + cpc_name=dict(required=True, type='str'), + partition_name=dict(required=True, type='str'), + name=dict(required=True, type='str'), + state=dict(required=True, type='str', + choices=['absent', 'present']), + properties=dict(required=False, type='dict', default=None), + log_file=dict(required=False, type='str', default=None), + _faked_session=dict(required=False, type='raw'), + ) + assert ansible_mod_cls.call_args == \ + mock.call(argument_spec=expected_argument_spec, + supports_check_mode=True) + + # Assert call to perform_task() + assert perform_task_func.call_args == mock.call(params, check_mode) + + # Assert call to exit_json() + assert mod_obj.exit_json.call_args == \ + mock.call(changed=perform_task_changed, hba=perform_task_result) + + # Assert no call to fail_json() + assert mod_obj.fail_json.called is False + + +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_hba.perform_task", + autospec=True) +@mock.patch("plugins.modules.zhmc_hba.AnsibleModule", + autospec=True) +def test_main_param_error( + ansible_mod_cls, perform_task_func, check_mode): + """ + Test main() with ParameterError being raised in perform_task(). + """ + + # Module invocation + params = { + 'hmc_host': 'fake-host', + 'hmc_auth': dict(userid='fake-userid', + password='fake-password'), + 'cpc_name': 'fake-cpc-name', + 'partition_name': 'fake-partition-name', + 'name': 'fake-hba-name', + 'state': 'absent', + 'log_file': None, + } + + # Exception raised by perform_task() + perform_task_exc = module_utils.ParameterError("fake message") + + # Prepare mocks + mod_obj = ansible_mod_cls.return_value + mod_obj.params = params + mod_obj.check_mode = check_mode + mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) + mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) + perform_task_func.mock.configure_mock(side_effect=perform_task_exc) + + # Exercise the code to be tested + with pytest.raises(SystemExit) as exc_info: + zhmc_hba.main() + exit_code = exc_info.value.args[0] + + # Assert module exit code + assert exit_code == 1 + + # Assert call to perform_task() + assert perform_task_func.call_args == mock.call(params, check_mode) + + # Assert call to fail_json() + assert mod_obj.fail_json.call_args == \ + mock.call(msg="ParameterError: fake message") + + # Assert no call to exit_json() + assert mod_obj.exit_json.called is False + + +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_hba.ensure_absent", + autospec=True) +@mock.patch("plugins.modules.zhmc_hba.ensure_present", + autospec=True) +def test_pt_present( + ensure_present_func, ensure_absent_func, check_mode): + """ + Test perform_task() with state 'present'. + """ + + # Prepare input arguments + params = { + 'state': 'present', + 'log_file': None, + } + + # Prepare return values + changed = False + result = { + 'fake-prop': 'fake-value', + } + + # Prepare mocks + ensure_present_func.return_value = (changed, result) + + # Exercise code + actual_changed, actual_result = zhmc_hba.perform_task( + params, check_mode) + + # Assert return values + assert actual_changed == changed + assert actual_result == result + + # Assert call to the desired action function + assert ensure_present_func.call_args == mock.call(params, check_mode) + + # Assert no call to the other action functions + assert ensure_absent_func.called is False + + +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_hba.ensure_absent", + autospec=True) +@mock.patch("plugins.modules.zhmc_hba.ensure_present", + autospec=True) +def test_pt_absent( + ensure_present_func, ensure_absent_func, check_mode): """ - Unit tests for the perform_task() function. + Test perform_task() with state 'absent'. """ - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_hba.ensure_absent", - autospec=True) - @mock.patch("plugins.modules.zhmc_hba.ensure_present", - autospec=True) - def test_pt_present( - self, ensure_present_func, ensure_absent_func, check_mode): - """ - Test perform_task() with state 'present'. - """ - - # Prepare input arguments - params = { - 'state': 'present', - 'log_file': None, - } - - # Prepare return values - changed = False - result = { - 'fake-prop': 'fake-value', - } - - # Prepare mocks - ensure_present_func.return_value = (changed, result) - - # Exercise code - actual_changed, actual_result = zhmc_hba.perform_task( - params, check_mode) - - # Assert return values - assert actual_changed == changed - assert actual_result == result - - # Assert call to the desired action function - assert ensure_present_func.call_args == mock.call(params, check_mode) - - # Assert no call to the other action functions - assert ensure_absent_func.called is False - - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_hba.ensure_absent", - autospec=True) - @mock.patch("plugins.modules.zhmc_hba.ensure_present", - autospec=True) - def test_pt_absent( - self, ensure_present_func, ensure_absent_func, check_mode): - """ - Test perform_task() with state 'absent'. - """ - - # Prepare input arguments - params = { - 'state': 'absent', - 'log_file': None, - } - - # Prepare return values - changed = True - result = { - 'fake-prop': 'fake-value', - } - - # Prepare mocks - ensure_absent_func.return_value = (changed, result) - - # Exercise code - actual_changed, actual_result = zhmc_hba.perform_task( - params, check_mode) - - # Assert return values - assert actual_changed == changed - assert actual_result == result - - # Assert call to the desired action function - assert ensure_absent_func.call_args == mock.call(params, check_mode) - - # Assert no call to the other action functions - assert ensure_present_func.called is False + # Prepare input arguments + params = { + 'state': 'absent', + 'log_file': None, + } + + # Prepare return values + changed = True + result = { + 'fake-prop': 'fake-value', + } + + # Prepare mocks + ensure_absent_func.return_value = (changed, result) + + # Exercise code + actual_changed, actual_result = zhmc_hba.perform_task( + params, check_mode) + + # Assert return values + assert actual_changed == changed + assert actual_result == result + + # Assert call to the desired action function + assert ensure_absent_func.call_args == mock.call(params, check_mode) + + # Assert no call to the other action functions + assert ensure_present_func.called is False # The other functions of the module are tested with function tests. diff --git a/tests/unit/test_nic.py b/tests/unit/test_nic.py index cdfae34b0..f94a8099c 100755 --- a/tests/unit/test_nic.py +++ b/tests/unit/test_nic.py @@ -20,242 +20,234 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock +import pytest from plugins.modules import zhmc_nic from plugins.module_utils import common as module_utils -class TestZhmcNicMain: +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_nic.perform_task", + autospec=True) +@mock.patch("plugins.modules.zhmc_nic.AnsibleModule", + autospec=True) +def test_main_success( + ansible_mod_cls, perform_task_func, check_mode): """ - Unit tests for the main() function. + Test main() with all required module parameters. """ - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_nic.perform_task", - autospec=True) - @mock.patch("plugins.modules.zhmc_nic.AnsibleModule", - autospec=True) - def test_main_success( - self, ansible_mod_cls, perform_task_func, check_mode): - """ - Test main() with all required module parameters. - """ - - # Module invocation - params = { - 'hmc_host': 'fake-host', - 'hmc_auth': dict(userid='fake-userid', - password='fake-password'), - 'cpc_name': 'fake-cpc-name', - 'partition_name': 'fake-partition-name', - 'name': 'fake-nic-name', - 'state': 'absent', - 'log_file': None, - } - - # Return values of perform_task() - perform_task_changed = True - perform_task_result = {} - - # Prepare mocks - mod_obj = ansible_mod_cls.return_value - mod_obj.params = params - mod_obj.check_mode = check_mode - mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) - mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) - perform_task_func.return_value = (perform_task_changed, - perform_task_result) - - # Exercise the code to be tested - with pytest.raises(SystemExit) as exc_info: - zhmc_nic.main() - exit_code = exc_info.value.args[0] - - # Assert module exit code - assert exit_code == 0 - - # Assert call to AnsibleModule() - expected_argument_spec = dict( - hmc_host=dict(required=True, type='raw'), - hmc_auth=dict( - required=True, - type='dict', - options=dict( - userid=dict(required=False, type='str', default=None), - password=dict(required=False, type='str', default=None, - no_log=True), - session_id=dict(required=False, type='str', default=None, - no_log=True), - ca_certs=dict(required=False, type='str', default=None), - verify=dict(required=False, type='bool', default=True), - ), + # Module invocation + params = { + 'hmc_host': 'fake-host', + 'hmc_auth': dict(userid='fake-userid', + password='fake-password'), + 'cpc_name': 'fake-cpc-name', + 'partition_name': 'fake-partition-name', + 'name': 'fake-nic-name', + 'state': 'absent', + 'log_file': None, + } + + # Return values of perform_task() + perform_task_changed = True + perform_task_result = {} + + # Prepare mocks + mod_obj = ansible_mod_cls.return_value + mod_obj.params = params + mod_obj.check_mode = check_mode + mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) + mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) + perform_task_func.return_value = (perform_task_changed, + perform_task_result) + + # Exercise the code to be tested + with pytest.raises(SystemExit) as exc_info: + zhmc_nic.main() + exit_code = exc_info.value.args[0] + + # Assert module exit code + assert exit_code == 0 + + # Assert call to AnsibleModule() + expected_argument_spec = dict( + hmc_host=dict(required=True, type='raw'), + hmc_auth=dict( + required=True, + type='dict', + options=dict( + userid=dict(required=False, type='str', default=None), + password=dict(required=False, type='str', default=None, + no_log=True), + session_id=dict(required=False, type='str', default=None, + no_log=True), + ca_certs=dict(required=False, type='str', default=None), + verify=dict(required=False, type='bool', default=True), ), - cpc_name=dict(required=True, type='str'), - partition_name=dict(required=True, type='str'), - name=dict(required=True, type='str'), - state=dict(required=True, type='str', - choices=['absent', 'present', 'facts']), - properties=dict(required=False, type='dict', default=None), - log_file=dict(required=False, type='str', default=None), - _faked_session=dict(required=False, type='raw'), - ) - assert ansible_mod_cls.call_args == \ - mock.call(argument_spec=expected_argument_spec, - supports_check_mode=True) - - # Assert call to perform_task() - assert perform_task_func.call_args == mock.call(params, check_mode) - - # Assert call to exit_json() - assert mod_obj.exit_json.call_args == \ - mock.call(changed=perform_task_changed, nic=perform_task_result) - - # Assert no call to fail_json() - assert mod_obj.fail_json.called is False - - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_nic.perform_task", - autospec=True) - @mock.patch("plugins.modules.zhmc_nic.AnsibleModule", - autospec=True) - def test_main_param_error( - self, ansible_mod_cls, perform_task_func, check_mode): - """ - Test main() with ParameterError being raised in perform_task(). - """ - - # Module invocation - params = { - 'hmc_host': 'fake-host', - 'hmc_auth': dict(userid='fake-userid', - password='fake-password'), - 'cpc_name': 'fake-cpc-name', - 'partition_name': 'fake-partition-name', - 'name': 'fake-nic-name', - 'state': 'absent', - 'log_file': None, - } - - # Exception raised by perform_task() - perform_task_exc = module_utils.ParameterError("fake message") - - # Prepare mocks - mod_obj = ansible_mod_cls.return_value - mod_obj.params = params - mod_obj.check_mode = check_mode - mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) - mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) - perform_task_func.mock.configure_mock(side_effect=perform_task_exc) - - # Exercise the code to be tested - with pytest.raises(SystemExit) as exc_info: - zhmc_nic.main() - exit_code = exc_info.value.args[0] - - # Assert module exit code - assert exit_code == 1 - - # Assert call to perform_task() - assert perform_task_func.call_args == mock.call(params, check_mode) - - # Assert call to fail_json() - assert mod_obj.fail_json.call_args == \ - mock.call(msg="ParameterError: fake message") - - # Assert no call to exit_json() - assert mod_obj.exit_json.called is False - - -class TestZhmcNicPerformTask: + ), + cpc_name=dict(required=True, type='str'), + partition_name=dict(required=True, type='str'), + name=dict(required=True, type='str'), + state=dict(required=True, type='str', + choices=['absent', 'present', 'facts']), + properties=dict(required=False, type='dict', default=None), + log_file=dict(required=False, type='str', default=None), + _faked_session=dict(required=False, type='raw'), + ) + assert ansible_mod_cls.call_args == \ + mock.call(argument_spec=expected_argument_spec, + supports_check_mode=True) + + # Assert call to perform_task() + assert perform_task_func.call_args == mock.call(params, check_mode) + + # Assert call to exit_json() + assert mod_obj.exit_json.call_args == \ + mock.call(changed=perform_task_changed, nic=perform_task_result) + + # Assert no call to fail_json() + assert mod_obj.fail_json.called is False + + +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_nic.perform_task", + autospec=True) +@mock.patch("plugins.modules.zhmc_nic.AnsibleModule", + autospec=True) +def test_main_param_error( + ansible_mod_cls, perform_task_func, check_mode): + """ + Test main() with ParameterError being raised in perform_task(). + """ + + # Module invocation + params = { + 'hmc_host': 'fake-host', + 'hmc_auth': dict(userid='fake-userid', + password='fake-password'), + 'cpc_name': 'fake-cpc-name', + 'partition_name': 'fake-partition-name', + 'name': 'fake-nic-name', + 'state': 'absent', + 'log_file': None, + } + + # Exception raised by perform_task() + perform_task_exc = module_utils.ParameterError("fake message") + + # Prepare mocks + mod_obj = ansible_mod_cls.return_value + mod_obj.params = params + mod_obj.check_mode = check_mode + mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) + mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) + perform_task_func.mock.configure_mock(side_effect=perform_task_exc) + + # Exercise the code to be tested + with pytest.raises(SystemExit) as exc_info: + zhmc_nic.main() + exit_code = exc_info.value.args[0] + + # Assert module exit code + assert exit_code == 1 + + # Assert call to perform_task() + assert perform_task_func.call_args == mock.call(params, check_mode) + + # Assert call to fail_json() + assert mod_obj.fail_json.call_args == \ + mock.call(msg="ParameterError: fake message") + + # Assert no call to exit_json() + assert mod_obj.exit_json.called is False + + +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_nic.ensure_absent", + autospec=True) +@mock.patch("plugins.modules.zhmc_nic.ensure_present", + autospec=True) +def test_pt_present( + ensure_present_func, ensure_absent_func, check_mode): + """ + Test perform_task() with state 'present'. + """ + + # Prepare input arguments + params = { + 'state': 'present', + 'log_file': None, + } + + # Prepare return values + changed = False + result = { + 'fake-prop': 'fake-value', + } + + # Prepare mocks + ensure_present_func.return_value = (changed, result) + + # Exercise code + actual_changed, actual_result = zhmc_nic.perform_task( + params, check_mode) + + # Assert return values + assert actual_changed == changed + assert actual_result == result + + # Assert call to the desired action function + assert ensure_present_func.call_args == mock.call(params, check_mode) + + # Assert no call to the other action functions + assert ensure_absent_func.called is False + + +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_nic.ensure_absent", + autospec=True) +@mock.patch("plugins.modules.zhmc_nic.ensure_present", + autospec=True) +def test_pt_absent( + ensure_present_func, ensure_absent_func, check_mode): """ - Unit tests for the perform_task() function. + Test perform_task() with state 'absent'. """ - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_nic.ensure_absent", - autospec=True) - @mock.patch("plugins.modules.zhmc_nic.ensure_present", - autospec=True) - def test_pt_present( - self, ensure_present_func, ensure_absent_func, check_mode): - """ - Test perform_task() with state 'present'. - """ - - # Prepare input arguments - params = { - 'state': 'present', - 'log_file': None, - } - - # Prepare return values - changed = False - result = { - 'fake-prop': 'fake-value', - } - - # Prepare mocks - ensure_present_func.return_value = (changed, result) - - # Exercise code - actual_changed, actual_result = zhmc_nic.perform_task( - params, check_mode) - - # Assert return values - assert actual_changed == changed - assert actual_result == result - - # Assert call to the desired action function - assert ensure_present_func.call_args == mock.call(params, check_mode) - - # Assert no call to the other action functions - assert ensure_absent_func.called is False - - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_nic.ensure_absent", - autospec=True) - @mock.patch("plugins.modules.zhmc_nic.ensure_present", - autospec=True) - def test_pt_absent( - self, ensure_present_func, ensure_absent_func, check_mode): - """ - Test perform_task() with state 'absent'. - """ - - # Prepare input arguments - params = { - 'state': 'absent', - 'log_file': None, - } - - # Prepare return values - changed = True - result = { - 'fake-prop': 'fake-value', - } - - # Prepare mocks - ensure_absent_func.return_value = (changed, result) - - # Exercise code - actual_changed, actual_result = zhmc_nic.perform_task( - params, check_mode) - - # Assert return values - assert actual_changed == changed - assert actual_result == result - - # Assert call to the desired action function - assert ensure_absent_func.call_args == mock.call(params, check_mode) - - # Assert no call to the other action functions - assert ensure_present_func.called is False + # Prepare input arguments + params = { + 'state': 'absent', + 'log_file': None, + } + + # Prepare return values + changed = True + result = { + 'fake-prop': 'fake-value', + } + + # Prepare mocks + ensure_absent_func.return_value = (changed, result) + + # Exercise code + actual_changed, actual_result = zhmc_nic.perform_task( + params, check_mode) + + # Assert return values + assert actual_changed == changed + assert actual_result == result + + # Assert call to the desired action function + assert ensure_absent_func.call_args == mock.call(params, check_mode) + + # Assert no call to the other action functions + assert ensure_present_func.called is False # The other functions of the module are tested with function tests. diff --git a/tests/unit/test_partition.py b/tests/unit/test_partition.py index fce72b4ae..fbebda718 100755 --- a/tests/unit/test_partition.py +++ b/tests/unit/test_partition.py @@ -20,7 +20,6 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import unittest from unittest import mock import re import pdb @@ -32,300 +31,293 @@ from plugins.module_utils import common as module_utils -class TestZhmcPartitionMain(unittest.TestCase): +@mock.patch("plugins.modules.zhmc_partition.perform_task", + autospec=True) +@mock.patch("plugins.modules.zhmc_partition.AnsibleModule", + autospec=True) +def test_main_success(ansible_mod_cls, perform_task_func): """ - Unit tests for the main() function. + Test main() with all required module parameters. """ - @mock.patch("plugins.modules.zhmc_partition.perform_task", - autospec=True) - @mock.patch("plugins.modules.zhmc_partition.AnsibleModule", - autospec=True) - def test_main_success(self, ansible_mod_cls, perform_task_func): - """ - Test main() with all required module parameters. - """ - - # Module invocation - params = { - 'hmc_host': 'fake-host', - 'hmc_auth': dict(userid='fake-userid', - password='fake-password'), - 'cpc_name': 'fake-cpc-name', - 'name': 'fake-name', - 'state': 'absent', - 'select_properties': None, - 'image_name': None, - 'image_file': None, - 'ins_file': None, - 'properties': None, - 'expand_storage_groups': False, - 'expand_crypto_adapters': False, - 'log_file': None, - } - check_mode = False - - # Return values of perform_task() - perform_task_changed = True - perform_task_result = {} - - # Prepare mocks - mod_obj = ansible_mod_cls.return_value - mod_obj.params = params - mod_obj.check_mode = check_mode - mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) - mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) - perform_task_func.return_value = (perform_task_changed, - perform_task_result) - - # Exercise code - with self.assertRaises(SystemExit) as cm: - zhmc_partition.main() - exit_code = cm.exception.args[0] - - # Assert module exit code - assert exit_code == 0 - - # Assert call to AnsibleModule() - expected_argument_spec = dict( - hmc_host=dict(required=True, type='raw'), - hmc_auth=dict( - required=True, - type='dict', - options=dict( - userid=dict(required=False, type='str', default=None), - password=dict(required=False, type='str', default=None, - no_log=True), - session_id=dict(required=False, type='str', default=None, - no_log=True), - ca_certs=dict(required=False, type='str', default=None), - verify=dict(required=False, type='bool', default=True), - ), + # Module invocation + params = { + 'hmc_host': 'fake-host', + 'hmc_auth': dict(userid='fake-userid', + password='fake-password'), + 'cpc_name': 'fake-cpc-name', + 'name': 'fake-name', + 'state': 'absent', + 'select_properties': None, + 'image_name': None, + 'image_file': None, + 'ins_file': None, + 'properties': None, + 'expand_storage_groups': False, + 'expand_crypto_adapters': False, + 'log_file': None, + } + check_mode = False + + # Return values of perform_task() + perform_task_changed = True + perform_task_result = {} + + # Prepare mocks + mod_obj = ansible_mod_cls.return_value + mod_obj.params = params + mod_obj.check_mode = check_mode + mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) + mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) + perform_task_func.return_value = (perform_task_changed, + perform_task_result) + + # Exercise code + with pytest.raises(SystemExit) as exc_info: + zhmc_partition.main() + exit_code = exc_info.value.args[0] + + # Assert module exit code + assert exit_code == 0 + + # Assert call to AnsibleModule() + expected_argument_spec = dict( + hmc_host=dict(required=True, type='raw'), + hmc_auth=dict( + required=True, + type='dict', + options=dict( + userid=dict(required=False, type='str', default=None), + password=dict(required=False, type='str', default=None, + no_log=True), + session_id=dict(required=False, type='str', default=None, + no_log=True), + ca_certs=dict(required=False, type='str', default=None), + verify=dict(required=False, type='bool', default=True), ), - cpc_name=dict(required=True, type='str'), - name=dict(required=True, type='str'), - state=dict(required=True, type='str', - choices=['absent', 'stopped', 'active', 'iso_mount', - 'iso_unmount', 'facts']), - select_properties=dict(required=False, type='list', elements='str', - default=None), - properties=dict(required=False, type='dict', default=None), - image_name=dict(required=False, type='str', default=None), - image_file=dict(required=False, type='str', default=None), - ins_file=dict(required=False, type='str', default=None), - expand_storage_groups=dict(required=False, type='bool', - default=False), - expand_crypto_adapters=dict(required=False, type='bool', - default=False), - log_file=dict(required=False, type='str', default=None), - _faked_session=dict(required=False, type='raw'), - ) - assert ansible_mod_cls.call_args == \ - mock.call(argument_spec=expected_argument_spec, - supports_check_mode=True) - - # Assert call to perform_task() - assert perform_task_func.call_args == mock.call(params, check_mode) - - # Assert call to exit_json() - assert mod_obj.exit_json.call_args == \ - mock.call(changed=perform_task_changed, - partition=perform_task_result) - - # Assert no call to fail_json() - assert mod_obj.fail_json.called is False - - @mock.patch("plugins.modules.zhmc_partition.perform_task", - autospec=True) - @mock.patch("plugins.modules.zhmc_partition.AnsibleModule", - autospec=True) - def test_main_param_error(self, ansible_mod_cls, perform_task_func): - """ - Test main() with ParameterError being raised in perform_task(). - """ - - # Module invocation - params = { - 'hmc_host': 'fake-host', - 'hmc_auth': dict(userid='fake-userid', - password='fake-password'), - 'cpc_name': 'fake-cpc-name', - 'name': 'fake-name', - 'state': 'absent', - 'select_properties': None, - 'image_name': None, - 'image_file': None, - 'ins_file': None, - 'properties': None, - 'expand_storage_groups': False, - 'expand_crypto_adapters': False, - 'log_file': None, - } - check_mode = False - - # Exception raised by perform_task() - perform_task_exc = module_utils.ParameterError("fake message") - - # Prepare mocks - mod_obj = ansible_mod_cls.return_value - mod_obj.params = params - mod_obj.check_mode = check_mode - mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) - mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) - perform_task_func.mock.configure_mock(side_effect=perform_task_exc) - - # Exercise code - with self.assertRaises(SystemExit) as cm: - zhmc_partition.main() - exit_code = cm.exception.args[0] - - # Assert module exit code - assert exit_code == 1 - - # Assert call to perform_task() - assert perform_task_func.call_args == mock.call(params, check_mode) - - # Assert call to fail_json() - assert mod_obj.fail_json.call_args == \ - mock.call(msg="ParameterError: fake message") - - # Assert no call to exit_json() - assert mod_obj.exit_json.called is False - - -class TestZhmcPartitionPerformTask(unittest.TestCase): + ), + cpc_name=dict(required=True, type='str'), + name=dict(required=True, type='str'), + state=dict(required=True, type='str', + choices=['absent', 'stopped', 'active', 'iso_mount', + 'iso_unmount', 'facts']), + select_properties=dict(required=False, type='list', elements='str', + default=None), + properties=dict(required=False, type='dict', default=None), + image_name=dict(required=False, type='str', default=None), + image_file=dict(required=False, type='str', default=None), + ins_file=dict(required=False, type='str', default=None), + expand_storage_groups=dict(required=False, type='bool', + default=False), + expand_crypto_adapters=dict(required=False, type='bool', + default=False), + log_file=dict(required=False, type='str', default=None), + _faked_session=dict(required=False, type='raw'), + ) + assert ansible_mod_cls.call_args == \ + mock.call(argument_spec=expected_argument_spec, + supports_check_mode=True) + + # Assert call to perform_task() + assert perform_task_func.call_args == mock.call(params, check_mode) + + # Assert call to exit_json() + assert mod_obj.exit_json.call_args == \ + mock.call(changed=perform_task_changed, + partition=perform_task_result) + + # Assert no call to fail_json() + assert mod_obj.fail_json.called is False + + +@mock.patch("plugins.modules.zhmc_partition.perform_task", + autospec=True) +@mock.patch("plugins.modules.zhmc_partition.AnsibleModule", + autospec=True) +def test_main_param_error(ansible_mod_cls, perform_task_func): """ - Unit tests for the perform_task() function. + Test main() with ParameterError being raised in perform_task(). """ - @mock.patch("plugins.modules.zhmc_partition.ensure_absent", - autospec=True) - @mock.patch("plugins.modules.zhmc_partition.ensure_active", - autospec=True) - @mock.patch("plugins.modules.zhmc_partition.ensure_stopped", - autospec=True) - def test_pt_active(self, ensure_stopped_func, ensure_active_func, - ensure_absent_func): - """ - Test perform_task() with state 'active'. - """ - - # Prepare input arguments - params = { - 'state': 'active', - 'log_file': None, - } - check_mode = True - - # Prepare return values - changed = False - result = { - 'fake-prop': 'fake-value', - } - - # Prepare mocks - ensure_active_func.return_value = (changed, result) - - # Exercise code - actual_changed, actual_result = zhmc_partition.perform_task( - params, check_mode) - - # Assert return values - assert actual_changed == changed - assert actual_result == result - - # Assert call to the desired action function - assert ensure_active_func.call_args == mock.call(params, check_mode) - - # Assert no call to the other action functions - assert ensure_stopped_func.called is False - assert ensure_absent_func.called is False - - @mock.patch("plugins.modules.zhmc_partition.ensure_absent", - autospec=True) - @mock.patch("plugins.modules.zhmc_partition.ensure_active", - autospec=True) - @mock.patch("plugins.modules.zhmc_partition.ensure_stopped", - autospec=True) - def test_pt_stopped(self, ensure_stopped_func, ensure_active_func, - ensure_absent_func): - """ - Test perform_task() with state 'stopped'. - """ - - # Prepare input arguments - params = { - 'state': 'stopped', - 'log_file': None, - } - check_mode = True - - # Prepare return values - changed = True - result = { - 'fake-prop': 'fake-value', - } - - # Prepare mocks - ensure_stopped_func.return_value = (changed, result) - - # Exercise code - actual_changed, actual_result = zhmc_partition.perform_task( - params, check_mode) - - # Assert return values - assert actual_changed == changed - assert actual_result == result - - # Assert call to the desired action function - assert ensure_stopped_func.call_args == mock.call(params, check_mode) - - # Assert no call to the other action functions - assert ensure_active_func.called is False - assert ensure_absent_func.called is False - - @mock.patch("plugins.modules.zhmc_partition.ensure_absent", - autospec=True) - @mock.patch("plugins.modules.zhmc_partition.ensure_active", - autospec=True) - @mock.patch("plugins.modules.zhmc_partition.ensure_stopped", - autospec=True) - def test_pt_absent(self, ensure_stopped_func, ensure_active_func, - ensure_absent_func): - """ - Test perform_task() with state 'absent'. - """ - - # Prepare input arguments - params = { - 'state': 'absent', - 'log_file': None, - } - check_mode = False - - # Prepare return values - changed = True - result = { - 'fake-prop': 'fake-value', - } - - # Prepare mocks - ensure_absent_func.return_value = (changed, result) - - # Exercise code - actual_changed, actual_result = zhmc_partition.perform_task( - params, check_mode) - - # Assert return values - assert actual_changed == changed - assert actual_result == result - - # Assert call to the desired action function - assert ensure_absent_func.call_args == mock.call(params, check_mode) - - # Assert no call to the other action functions - assert ensure_active_func.called is False - assert ensure_stopped_func.called is False + # Module invocation + params = { + 'hmc_host': 'fake-host', + 'hmc_auth': dict(userid='fake-userid', + password='fake-password'), + 'cpc_name': 'fake-cpc-name', + 'name': 'fake-name', + 'state': 'absent', + 'select_properties': None, + 'image_name': None, + 'image_file': None, + 'ins_file': None, + 'properties': None, + 'expand_storage_groups': False, + 'expand_crypto_adapters': False, + 'log_file': None, + } + check_mode = False + + # Exception raised by perform_task() + perform_task_exc = module_utils.ParameterError("fake message") + + # Prepare mocks + mod_obj = ansible_mod_cls.return_value + mod_obj.params = params + mod_obj.check_mode = check_mode + mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) + mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) + perform_task_func.mock.configure_mock(side_effect=perform_task_exc) + + # Exercise code + with pytest.raises(SystemExit) as exc_info: + zhmc_partition.main() + exit_code = exc_info.value.args[0] + + # Assert module exit code + assert exit_code == 1 + + # Assert call to perform_task() + assert perform_task_func.call_args == mock.call(params, check_mode) + + # Assert call to fail_json() + assert mod_obj.fail_json.call_args == \ + mock.call(msg="ParameterError: fake message") + + # Assert no call to exit_json() + assert mod_obj.exit_json.called is False + + +@mock.patch("plugins.modules.zhmc_partition.ensure_absent", + autospec=True) +@mock.patch("plugins.modules.zhmc_partition.ensure_active", + autospec=True) +@mock.patch("plugins.modules.zhmc_partition.ensure_stopped", + autospec=True) +def test_pt_active(ensure_stopped_func, ensure_active_func, + ensure_absent_func): + """ + Test perform_task() with state 'active'. + """ + + # Prepare input arguments + params = { + 'state': 'active', + 'log_file': None, + } + check_mode = True + + # Prepare return values + changed = False + result = { + 'fake-prop': 'fake-value', + } + + # Prepare mocks + ensure_active_func.return_value = (changed, result) + + # Exercise code + actual_changed, actual_result = zhmc_partition.perform_task( + params, check_mode) + + # Assert return values + assert actual_changed == changed + assert actual_result == result + + # Assert call to the desired action function + assert ensure_active_func.call_args == mock.call(params, check_mode) + + # Assert no call to the other action functions + assert ensure_stopped_func.called is False + assert ensure_absent_func.called is False + + +@mock.patch("plugins.modules.zhmc_partition.ensure_absent", + autospec=True) +@mock.patch("plugins.modules.zhmc_partition.ensure_active", + autospec=True) +@mock.patch("plugins.modules.zhmc_partition.ensure_stopped", + autospec=True) +def test_pt_stopped(ensure_stopped_func, ensure_active_func, + ensure_absent_func): + """ + Test perform_task() with state 'stopped'. + """ + + # Prepare input arguments + params = { + 'state': 'stopped', + 'log_file': None, + } + check_mode = True + + # Prepare return values + changed = True + result = { + 'fake-prop': 'fake-value', + } + + # Prepare mocks + ensure_stopped_func.return_value = (changed, result) + + # Exercise code + actual_changed, actual_result = zhmc_partition.perform_task( + params, check_mode) + + # Assert return values + assert actual_changed == changed + assert actual_result == result + + # Assert call to the desired action function + assert ensure_stopped_func.call_args == mock.call(params, check_mode) + + # Assert no call to the other action functions + assert ensure_active_func.called is False + assert ensure_absent_func.called is False + + +@mock.patch("plugins.modules.zhmc_partition.ensure_absent", + autospec=True) +@mock.patch("plugins.modules.zhmc_partition.ensure_active", + autospec=True) +@mock.patch("plugins.modules.zhmc_partition.ensure_stopped", + autospec=True) +def test_pt_absent(ensure_stopped_func, ensure_active_func, + ensure_absent_func): + """ + Test perform_task() with state 'absent'. + """ + + # Prepare input arguments + params = { + 'state': 'absent', + 'log_file': None, + } + check_mode = False + + # Prepare return values + changed = True + result = { + 'fake-prop': 'fake-value', + } + + # Prepare mocks + ensure_absent_func.return_value = (changed, result) + + # Exercise code + actual_changed, actual_result = zhmc_partition.perform_task( + params, check_mode) + + # Assert return values + assert actual_changed == changed + assert actual_result == result + + # Assert call to the desired action function + assert ensure_absent_func.call_args == mock.call(params, check_mode) + + # Assert no call to the other action functions + assert ensure_active_func.called is False + assert ensure_stopped_func.called is False # Faked CPC in DPM mode that is used for all tests @@ -366,8 +358,8 @@ def mocked_cpc(): return cpc -PARTITION_CREATE_CHECK_MODE_PARTITION_TESTCASES = [ - # Testcases for test_partition_create_check_mode_partition() +PART_CREATE_CHECK_MODE_PARTITION_TESTCASES = [ + # Testcases for test_part_create_check_mode_partition() # The list items are tuples with the following items: # - desc (string): description of the testcase. # - create_props (dict): HMC-formatted properties for the create_props @@ -651,8 +643,8 @@ def mocked_cpc(): @pytest.mark.parametrize( "desc, create_props, update_props, exp_props, exp_exc_type, " "exp_exc_pattern, run", - PARTITION_CREATE_CHECK_MODE_PARTITION_TESTCASES) -def test_partition_create_check_mode_partition( + PART_CREATE_CHECK_MODE_PARTITION_TESTCASES) +def test_part_create_check_mode_partition( desc, create_props, update_props, exp_props, exp_exc_type, exp_exc_pattern, run): """ @@ -669,7 +661,7 @@ def test_partition_create_check_mode_partition( with pytest.raises(exp_exc_type) as exc_info: if run == 'pdb': - pdb.set_trace() + pdb.set_trace() # pylint: disable=forgotten-debug-statement # The function to be tested part_obj = zhmc_partition.create_check_mode_partition( @@ -685,7 +677,7 @@ def test_partition_create_check_mode_partition( else: if run == 'pdb': - pdb.set_trace() + pdb.set_trace() # pylint: disable=forgotten-debug-statement # The function to be tested part_obj = zhmc_partition.create_check_mode_partition( diff --git a/tests/unit/test_virtual_function.py b/tests/unit/test_virtual_function.py index c79d09895..ab0bd8380 100755 --- a/tests/unit/test_virtual_function.py +++ b/tests/unit/test_virtual_function.py @@ -20,243 +20,235 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import pytest from unittest import mock +import pytest from plugins.modules import zhmc_virtual_function from plugins.module_utils import common as module_utils -class TestZhmcVirtualFunctionMain: +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_virtual_function.perform_task", + autospec=True) +@mock.patch("plugins.modules.zhmc_virtual_function.AnsibleModule", + autospec=True) +def test_main_success( + ansible_mod_cls, perform_task_func, check_mode): """ - Unit tests for the main() function. + Test main() with all required module parameters. """ - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_virtual_function.perform_task", - autospec=True) - @mock.patch("plugins.modules.zhmc_virtual_function.AnsibleModule", - autospec=True) - def test_main_success( - self, ansible_mod_cls, perform_task_func, check_mode): - """ - Test main() with all required module parameters. - """ - - # Module invocation - params = { - 'hmc_host': 'fake-host', - 'hmc_auth': dict(userid='fake-userid', - password='fake-password'), - 'cpc_name': 'fake-cpc-name', - 'partition_name': 'fake-partition-name', - 'name': 'fake-vfunction-name', - 'state': 'absent', - 'log_file': None, - } - - # Return values of perform_task() - perform_task_changed = True - perform_task_result = {} - - # Prepare mocks - mod_obj = ansible_mod_cls.return_value - mod_obj.params = params - mod_obj.check_mode = check_mode - mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) - mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) - perform_task_func.return_value = (perform_task_changed, - perform_task_result) - - # Exercise the code to be tested - with pytest.raises(SystemExit) as exc_info: - zhmc_virtual_function.main() - exit_code = exc_info.value.args[0] - - # Assert module exit code - assert exit_code == 0 - - # Assert call to AnsibleModule() - expected_argument_spec = dict( - hmc_host=dict(required=True, type='raw'), - hmc_auth=dict( - required=True, - type='dict', - options=dict( - userid=dict(required=False, type='str', default=None), - password=dict(required=False, type='str', default=None, - no_log=True), - session_id=dict(required=False, type='str', default=None, - no_log=True), - ca_certs=dict(required=False, type='str', default=None), - verify=dict(required=False, type='bool', default=True), - ), + # Module invocation + params = { + 'hmc_host': 'fake-host', + 'hmc_auth': dict(userid='fake-userid', + password='fake-password'), + 'cpc_name': 'fake-cpc-name', + 'partition_name': 'fake-partition-name', + 'name': 'fake-vfunction-name', + 'state': 'absent', + 'log_file': None, + } + + # Return values of perform_task() + perform_task_changed = True + perform_task_result = {} + + # Prepare mocks + mod_obj = ansible_mod_cls.return_value + mod_obj.params = params + mod_obj.check_mode = check_mode + mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) + mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) + perform_task_func.return_value = (perform_task_changed, + perform_task_result) + + # Exercise the code to be tested + with pytest.raises(SystemExit) as exc_info: + zhmc_virtual_function.main() + exit_code = exc_info.value.args[0] + + # Assert module exit code + assert exit_code == 0 + + # Assert call to AnsibleModule() + expected_argument_spec = dict( + hmc_host=dict(required=True, type='raw'), + hmc_auth=dict( + required=True, + type='dict', + options=dict( + userid=dict(required=False, type='str', default=None), + password=dict(required=False, type='str', default=None, + no_log=True), + session_id=dict(required=False, type='str', default=None, + no_log=True), + ca_certs=dict(required=False, type='str', default=None), + verify=dict(required=False, type='bool', default=True), ), - cpc_name=dict(required=True, type='str'), - partition_name=dict(required=True, type='str'), - name=dict(required=True, type='str'), - state=dict(required=True, type='str', - choices=['absent', 'present']), - properties=dict(required=False, type='dict', default=None), - log_file=dict(required=False, type='str', default=None), - _faked_session=dict(required=False, type='raw'), - ) - assert ansible_mod_cls.call_args == \ - mock.call(argument_spec=expected_argument_spec, - supports_check_mode=True) - - # Assert call to perform_task() - assert perform_task_func.call_args == mock.call(params, check_mode) - - # Assert call to exit_json() - assert mod_obj.exit_json.call_args == \ - mock.call(changed=perform_task_changed, - virtual_function=perform_task_result) - - # Assert no call to fail_json() - assert mod_obj.fail_json.called is False - - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_virtual_function.perform_task", - autospec=True) - @mock.patch("plugins.modules.zhmc_virtual_function.AnsibleModule", - autospec=True) - def test_main_param_error( - self, ansible_mod_cls, perform_task_func, check_mode): - """ - Test main() with ParameterError being raised in perform_task(). - """ - - # Module invocation - params = { - 'hmc_host': 'fake-host', - 'hmc_auth': dict(userid='fake-userid', - password='fake-password'), - 'cpc_name': 'fake-cpc-name', - 'partition_name': 'fake-partition-name', - 'name': 'fake-vfunction-name', - 'state': 'absent', - 'log_file': None, - } - - # Exception raised by perform_task() - perform_task_exc = module_utils.ParameterError("fake message") - - # Prepare mocks - mod_obj = ansible_mod_cls.return_value - mod_obj.params = params - mod_obj.check_mode = check_mode - mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) - mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) - perform_task_func.mock.configure_mock(side_effect=perform_task_exc) - - # Exercise the code to be tested - with pytest.raises(SystemExit) as exc_info: - zhmc_virtual_function.main() - exit_code = exc_info.value.args[0] - - # Assert module exit code - assert exit_code == 1 - - # Assert call to perform_task() - assert perform_task_func.call_args == mock.call(params, check_mode) - - # Assert call to fail_json() - assert mod_obj.fail_json.call_args == \ - mock.call(msg="ParameterError: fake message") - - # Assert no call to exit_json() - assert mod_obj.exit_json.called is False - - -class TestZhmcVirtualFunctionPerformTask: + ), + cpc_name=dict(required=True, type='str'), + partition_name=dict(required=True, type='str'), + name=dict(required=True, type='str'), + state=dict(required=True, type='str', + choices=['absent', 'present']), + properties=dict(required=False, type='dict', default=None), + log_file=dict(required=False, type='str', default=None), + _faked_session=dict(required=False, type='raw'), + ) + assert ansible_mod_cls.call_args == \ + mock.call(argument_spec=expected_argument_spec, + supports_check_mode=True) + + # Assert call to perform_task() + assert perform_task_func.call_args == mock.call(params, check_mode) + + # Assert call to exit_json() + assert mod_obj.exit_json.call_args == \ + mock.call(changed=perform_task_changed, + virtual_function=perform_task_result) + + # Assert no call to fail_json() + assert mod_obj.fail_json.called is False + + +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_virtual_function.perform_task", + autospec=True) +@mock.patch("plugins.modules.zhmc_virtual_function.AnsibleModule", + autospec=True) +def test_main_param_error( + ansible_mod_cls, perform_task_func, check_mode): + """ + Test main() with ParameterError being raised in perform_task(). + """ + + # Module invocation + params = { + 'hmc_host': 'fake-host', + 'hmc_auth': dict(userid='fake-userid', + password='fake-password'), + 'cpc_name': 'fake-cpc-name', + 'partition_name': 'fake-partition-name', + 'name': 'fake-vfunction-name', + 'state': 'absent', + 'log_file': None, + } + + # Exception raised by perform_task() + perform_task_exc = module_utils.ParameterError("fake message") + + # Prepare mocks + mod_obj = ansible_mod_cls.return_value + mod_obj.params = params + mod_obj.check_mode = check_mode + mod_obj.fail_json.configure_mock(side_effect=SystemExit(1)) + mod_obj.exit_json.configure_mock(side_effect=SystemExit(0)) + perform_task_func.mock.configure_mock(side_effect=perform_task_exc) + + # Exercise the code to be tested + with pytest.raises(SystemExit) as exc_info: + zhmc_virtual_function.main() + exit_code = exc_info.value.args[0] + + # Assert module exit code + assert exit_code == 1 + + # Assert call to perform_task() + assert perform_task_func.call_args == mock.call(params, check_mode) + + # Assert call to fail_json() + assert mod_obj.fail_json.call_args == \ + mock.call(msg="ParameterError: fake message") + + # Assert no call to exit_json() + assert mod_obj.exit_json.called is False + + +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_virtual_function.ensure_absent", + autospec=True) +@mock.patch("plugins.modules.zhmc_virtual_function.ensure_present", + autospec=True) +def test_pt_present( + ensure_present_func, ensure_absent_func, check_mode): + """ + Test perform_task() with state 'present'. + """ + + # Prepare input arguments + params = { + 'state': 'present', + 'log_file': None, + } + + # Prepare return values + changed = False + result = { + 'fake-prop': 'fake-value', + } + + # Prepare mocks + ensure_present_func.return_value = (changed, result) + + # Exercise code + actual_changed, actual_result = zhmc_virtual_function.perform_task( + params, check_mode) + + # Assert return values + assert actual_changed == changed + assert actual_result == result + + # Assert call to the desired action function + assert ensure_present_func.call_args == mock.call(params, check_mode) + + # Assert no call to the other action functions + assert ensure_absent_func.called is False + + +@pytest.mark.parametrize( + "check_mode", [False, True]) +@mock.patch("plugins.modules.zhmc_virtual_function.ensure_absent", + autospec=True) +@mock.patch("plugins.modules.zhmc_virtual_function.ensure_present", + autospec=True) +def test_pt_absent( + ensure_present_func, ensure_absent_func, check_mode): """ - Unit tests for the perform_task() function. + Test perform_task() with state 'absent'. """ - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_virtual_function.ensure_absent", - autospec=True) - @mock.patch("plugins.modules.zhmc_virtual_function.ensure_present", - autospec=True) - def test_pt_present( - self, ensure_present_func, ensure_absent_func, check_mode): - """ - Test perform_task() with state 'present'. - """ - - # Prepare input arguments - params = { - 'state': 'present', - 'log_file': None, - } - - # Prepare return values - changed = False - result = { - 'fake-prop': 'fake-value', - } - - # Prepare mocks - ensure_present_func.return_value = (changed, result) - - # Exercise code - actual_changed, actual_result = zhmc_virtual_function.perform_task( - params, check_mode) - - # Assert return values - assert actual_changed == changed - assert actual_result == result - - # Assert call to the desired action function - assert ensure_present_func.call_args == mock.call(params, check_mode) - - # Assert no call to the other action functions - assert ensure_absent_func.called is False - - @pytest.mark.parametrize( - "check_mode", [False, True]) - @mock.patch("plugins.modules.zhmc_virtual_function.ensure_absent", - autospec=True) - @mock.patch("plugins.modules.zhmc_virtual_function.ensure_present", - autospec=True) - def test_pt_absent( - self, ensure_present_func, ensure_absent_func, check_mode): - """ - Test perform_task() with state 'absent'. - """ - - # Prepare input arguments - params = { - 'state': 'absent', - 'log_file': None, - } - - # Prepare return values - changed = True - result = { - 'fake-prop': 'fake-value', - } - - # Prepare mocks - ensure_absent_func.return_value = (changed, result) - - # Exercise code - actual_changed, actual_result = zhmc_virtual_function.perform_task( - params, check_mode) - - # Assert return values - assert actual_changed == changed - assert actual_result == result - - # Assert call to the desired action function - assert ensure_absent_func.call_args == mock.call(params, check_mode) - - # Assert no call to the other action functions - assert ensure_present_func.called is False + # Prepare input arguments + params = { + 'state': 'absent', + 'log_file': None, + } + + # Prepare return values + changed = True + result = { + 'fake-prop': 'fake-value', + } + + # Prepare mocks + ensure_absent_func.return_value = (changed, result) + + # Exercise code + actual_changed, actual_result = zhmc_virtual_function.perform_task( + params, check_mode) + + # Assert return values + assert actual_changed == changed + assert actual_result == result + + # Assert call to the desired action function + assert ensure_absent_func.call_args == mock.call(params, check_mode) + + # Assert no call to the other action functions + assert ensure_present_func.called is False # The other functions of the module are tested with function tests.