8. Development

This section only needs to be read by developers of the zhmcclient package. People that want to make a fix or develop some extension, and people that want to test the project are also considered developers for the purpose of this section.

8.1. Code of Conduct

Help us keep zhmcclient open and inclusive. Please read and follow our Code of Conduct.

8.2. Repository

The repository for zhmcclient is on GitHub:

https://github.com/zhmcclient/python-zhmcclient

8.3. Setting up the development environment

The development environment is pretty easy to set up.

Besides having a supported operating system with a supported Python version (see Supported environments), it is recommended that you set up a virtual Python environment.

Then, with a virtual Python environment active, clone the Git repo of this project and prepare the development environment with make develop:

$ git clone git@github.com:zhmcclient/python-zhmcclient.git
$ cd python-zhmcclient
$ make develop

This will install all prerequisites the package needs to run, as well as all prerequisites that you need for development.

Generally, this project uses Make to do things in the currently active Python environment. The command make help (or just make) displays a list of valid Make targets and a short description of what each target does.

8.4. Building the documentation

The ReadTheDocs (RTD) site is used to publish the documentation for the zhmcclient package at https://python-zhmcclient.readthedocs.io/

This page automatically gets updated whenever the master branch of the Git repo for this package changes.

In order to build the documentation locally from the Git work directory, issue:

$ make builddoc

The top-level document to open with a web browser will be build_doc/html/docs/index.html.

8.5. Testing

The zhmcclient project supports the following kinds of tests:

  • unit tests against a mocked HMC, using pytest

  • end2end tests against a real or mocked HMC, using pytest

  • install tests (Linux and MacOS only)

8.5.1. Running unit tests

To run the unit tests in the currently active Python environment, issue:

$ make test

The unit tests import the zhmcclient modules from the local directory, even when the zhmcclient package is installed in the Python environment.

By default, all unit tests are run. The TESTCASES environment variable can be used to limit the testcases that are run. Its value is passed to the -k option of the pytest command. For example:

$ TESTCASES=test_resource.py make test       # Run only this test source file
$ TESTCASES=test_func1  make test            # Run only this test function or test class
$ TESTCASES="test_func1 or test_func2" make test  # Run both of these test functions or classes

Additional options for the pytest command can be specified with the TESTOPTS environment variable. For example:

$ TESTOPTS='-x' make test                    # Stop after first test case failure
$ TESTOPTS='--pdb' make test                 # Invoke debugger on each test case failure

Invoke pytest --help for details on its options including the syntax of the -k option, or see pytest options.

To run the unit tests and some more commands that verify the project is in good shape in all supported Python environments, use Tox. The positional arguments of the tox command are passed to pytest using its -k option. For example:

$ tox                              # Run all tests on all supported Python versions
$ tox -e py38                      # Run all tests on Python 3.8
$ tox -e py38 test_resource.py     # Run only this test source file on Python 3.8
$ tox -e py38 TestInit             # Run only this test class on Python 3.8
$ tox -e py38 TestInit or TestSet  # pytest -k expressions are possible

8.5.2. Running end2end tests

Prepare an HMC inventory file that defines real and/or mocked HMCs the tests should be run against, and an HMC vault file with credentials for the real HMCs.

There are examples for these files, that describe their format in the comment header:

To run the end2end tests in the currently active Python environment, issue:

$ make end2end

The end2end tests import the zhmcclient modules from the local directory, even when the zhmcclient package is installed in the Python environment.

By default, the HMC inventory file named .zhmc_inventory.yaml in the home directory of the current user is used. A different path name can be specified with the TESTINVENTORY environment variable.

By default, the HMC vault file named .zhmc_vault.yaml in the home directory of the current user is used. A different path name can be specified with the TESTVAULT environment variable.

By default, the tests are run against the group name or HMC nickname default defined in the HMC inventory file. A different group name or HMC nickname can be specified with the TESTHMC environment variable.

Examples:

  • Run against group or HMC nickname ‘default’ using the specified HMC inventory and vault files:

    $ TESTINVENTORY=`./hmc_inventory.yaml` TESTVAULT=`./hmc_vault.yaml` make end2end
    
  • Run against group or HMC nickname ‘HMC1’ using the default HMC inventory and vault files:

    $ TESTHMC=`HMC1` make end2end
    

8.5.3. Running end2end tests against example mocked environments

The examples directory contains example mocked environments defined in the following YAML files:

  • examples/example_mocked_z16_classic.yaml - HMC with a z16 in classic mode

  • examples/example_mocked_z16_dpm.yaml - HMC with a z16 in DPM mode

It also contains an inventory and vault file for these mocked environments. The inventory file defines its default group to use these mocked environments:

  • examples/example_hmc_inventory.yaml

  • examples/example_hmc_vault.yaml

These mock environments can be used to run the end2end tests against, by executing:

$ make end2end_mocked

The end2end tests import the zhmcclient modules from the local directory, even when the zhmcclient package is installed in the Python environment.

8.5.4. Enabling logging during end2end tests

TODO: At this point, the `setup_logging()` function that enables the logging described in this section is not used in the end2end tests

The end2end tests have the ability to log the API calls to the zhmcclient library and the interactions with the (real or mocked) HMC.

By default, logging is set up such that the zhmcclient library logs messages with a log level of “warning” or higher, to stderr.

The log level and the components to be logged can be set using the ZHMC_LOG environment variable:

$ export ZHMC_LOG=COMP=LEVEL[,COMP=LEVEL[,...]]

Where:

  • COMP is one of: all, api, hmc.

  • LEVEL is one of: error, warning, info, debug.

For example, to enable logging of the zhmcclient API calls and the interactions with the HMC, use:

$ export ZHMC_LOG=api=debug,hmc=debug

or, shorter:

$ export ZHMC_LOG=all=debug

8.5.5. Test coverage

When unit or end2end tests are run locally, the pytest-cov plugin of pytest traces coverage data and adds that to the local .coverage file. Each test run adds data to that file.

At the end of a test run, pytest creates a HMTL formatted coverage report in the htmlcov directory. That report contains the data from the .coverage file, and thus represents all prior test runs since that file was created. If you want to see just the coverage caused by a single test run, remove the .coverage file manually, or run make clean.

When the tests are run in GitHub Actions, the same mechanism is used, and in addition the coverage data is reported to https://coveralls.io/github/zhmcclient/python-zhmcclient. The PR is updated with a comment linking to the coveralls.io data for the PR.

8.5.6. HMC inventory file

The HMC inventory file specifies HMCs and/or groups of HMCs to be used for any code that uses the zhmcclient.testutils module, such as the end2end tests, the example scripts, other zhmcclient projects, or even projects by users of the zhmcclient library.

The HMCs and HMC groups defined in the HMC inventory file have nicknames and the nickname to be used for end2end tests and the example scripts can be specified using the TESTHMC environment variable, for example:

$ TESTHMC=HMC1 make end2end             # run end2end tests against nickname "HMC1"

$ TESTHMC=HMC1 examples/list_cpcs.py    # run this example script against nickname "HMC1"

If no nickname is specified using the TESTHMC environment variable, the nickname “default” is used, for example:

$ make end2end             # run end2end tests against nickname "default""

$ examples/list_cpcs.py    # run this example script against nickname "default""

By default, the HMC inventory file ~/.zhmc_inventory.yaml is used. A different path name can be specified with the TESTINVENTORY environment variable.

The following describes the structure of the HMC inventory file:

all:                                # Nickname of the top-level HMC group; must be 'all'.

  hosts:                            # Definition of all HMCs, each with an item as follows:

    <hmc_nick>:                     # Nickname of an HMC; may be a DNS hostname, IP address,
                                    #   or arbitrary string.

      description: <string>         # Optional: One line description of the HMC.

      contact: <string>             # Optional: Informal reference to a contact for the HMC.

      access_via: <string>          # Optional: Reminder on network setup needed for access.

      ansible_host: <host>          # If real HMC: DNS hostname or IP address of HMC, if
                                    #   arbitrary string was used as HMC nickname.
                                    #   This can specify a single HMC or a list of redundant
                                    #   HMCs.

      mock_file: <path_name>        # If mocked HMC: Relative path name of HMC mock file.
      cpcs:                         # CPCs to test against. Can be a subset or all CPCs
                                    #   managed by the HMC.

        <cpc_name>:                 # CPC name.

          dpm_enabled: <bool>       # Whether the CPC is in DPM mode (true) or classic mode
                                    #   (false). This is used to include the CPC in pytest
                                    #   fixtures that select CPCs based on their mode.

          <prop_name>: <prop_value>  # Optional: Additional expected CPC properties, for
                                    #   use by test functions.

      <var_name>: <var_value>       # Optional: Additional variables for this HMC, for use
                                    #   by test functions.

  vars:                             # Optional: Additional variables for all HMCs, for use
                                    #   by test functions.
    <var_name>: <var_value>

  children:                         # Optional: HMC groups.

    <group_nick>:                   # Nickname of this HMC group.

      hosts:                        # The HMCs in this group.

        <hmc_nick>:                 # Reference to an HMC in this group via its nickname.

          ...                       # Optional: Additional variables to override the ones
                                    #   inherited from the parent HMC definition. Not
                                    #   normally needed.

      vars:                         # Optional: Additional variables for the HMCs in this
                                    #   group.
        <var_name>: <var_value>

      children:                     # Optional: Grand child groups. Only ever needed when
        ...                         #   using variable inheritance for some reason.
                                    #   Can be further nested.

Here is the example HMC inventory file examples/example_hmc_inventory.yaml:

---
# HMC inventory file for zhmcclient projects
#
# This file defines real HMCs and mocked HMCs (using the zhmcclient mock
# support) for use by the zhmcclient projects. Their credentials are defined
# in a corresponding HMC vault file.
#
# The format of HMC inventory files is described in
# https://python-zhmcclient.readthedocs.io/en/master/development.html#hmc-inventory-file

all:
  hosts:

    HMC1:
      description: "my dev systems"
      contact: "John Doe"
      access_via: "VPN to dev network"
      ansible_host: "10.11.12.13"
      cpcs:
        XYZ1:
          machine_type: "2964"
          dpm_enabled: true
        XYZ2:
          machine_type: "3906"
          dpm_enabled: true

    MOCKED_Z16_CLASSIC:
      description: "Example mocked HMC with a z16 in classic mode"
      mock_file: "example_mocked_z16_classic.yaml"
      cpcs:
        CPC1:
          machine_type: "3906"
          dpm_enabled: false

    MOCKED_Z16_DPM:
      description: "Example mocked HMC with a z16 in DPM mode"
      mock_file: "example_mocked_z16_dpm.yaml"
      cpcs:
        CPC1:
          machine_type: "3906"
          dpm_enabled: true

  children:

    default:
      hosts:
        MOCKED_Z16_CLASSIC:
        MOCKED_Z16_DPM:

    dev:
      hosts:
        HMC1:

In that example HMC inventory file, the following nicknames of single HMCs are defined:

The following nicknames of HMC groups are defined:

  • all - All HMCs, i.e. HMC1, MOCKED_Z16_CLASSIC, and MOCKED_Z16_DPM.

  • default - The HMCs with nicknames MOCKED_Z16_CLASSIC and MOCKED_Z16_DPM.

  • dev - The HMC with nickname HMC1.

The tests that use CPCs or resources within CPCs will be run against only the subset of CPCs that are defined in the cpcs variables of the HMC entries. In that example HMC inventory file, those are:

  • For HMC1: Only the CPCs XYZ1 and XYZ2.

  • For MOCKED_Z16_CLASSIC: Only the CPC CPC1.

  • For MOCKED_Z16_DPM: Only the CPC CPC1.

Any variables defined for the HMCs are available to the test functions via an HMCDefinition object. See pytest fixture hmc_session() for details.

The format of HMC inventory files is compatible with the format of Ansible inventory files in YAML format, with the following extensions:

  • Certain variables in the definition of HMC hosts have a defined meaning. See the format description above for details.

and the following limitations:

  • DNS host names or IP addresses with ranges (e.g. myhost[0:9].xyz.com) are not supported.

For more details on the format of Ansible inventory files, see Ansible: How to build your inventory.

8.5.7. HMC vault file

The HMC vault file specifies credentials for real HMCs to be used for any code that uses the zhmcclient.testutils module, such as the end2end tests, the example scripts, other zhmcclient projects, or even projects by users of the zhmcclient library.

It is required to have the HMC credentials in the HMC vault file; they cannot be specified in the HMC inventory file.

By default, the HMC vault file ~/.zhmc_vault.yaml is used. A different path name can be specified with the TESTVAULT environment variable.

The data items for HMCs in the HMC vault file are looked up using the HMC names from the HMC inventory file, so they must match.

The following describes the structure of the HMC vault file:

hmc_auth:

  <hmc_nick>:                     # Nickname of an HMC defined in the inventory file

    userid: <string>              # HMC userid. Required.

    password: <string>            # HMC password.
                                  # Exactly one of 'password', 'password_command' must be specified.

    password_command: <string>    # Command that retrieves the HMC password.

    password_timeout: <int>       # Timeout for password command, in seconds. Optional, default: 30

    verify: <bool>                # Indicates whether the server certificate returned
                                  #   by the HMC should be validated.
                                  # Optional, default: true

    ca_certs: <ca_certs>          # Used for verify_cert init parm of zhmcclient.Session.
                                  # Optional, default: none

<var_name>: <var_value>           # Any other variables are allowed but will be ignored

The password can either be specified directly in the file by using the password property, or by specifying a password command string using the password_command property. This allows lookup of passwords from some other password store (e.g. a vault) or the use of one-time passwords.

The password command string is executed in a shell child process, using the following shell:

  • bin/sh on Linux and MacOS (that cannot be overridden using the SHELL variable).

  • cmd.exe on Windows.

This means, the password command string may specify any constructs supported by the shell language.

If the password command has an exit code of 0 and has printed nothing on its standard error, it is considered to have succeeded, and its standard output is taken as the password after stripping leading and trailing whitespace.

Otherwise, the password command is considered to have failed, and its exit code and standard error are captured in an exception.

The password command string specified in the vault file may contain variables using a {var} syntax. These variables are expanded to the actual values before executing the command. The following variables are supported:

  • {host} - HMC host, i.e. IP address or DNS hostname

  • {userid} - HMC userid

For details about <ca_certs>, see the description of the verify_cert init parameter of the zhmcclient.Session class.

Here is the example HMC vault file examples/example_hmc_vault.yaml:

---
# HMC vault file for zhmcclient projects
#
# This file defines the credentials for real HMCs for use by the zhmcclient
# projects. Their HMC definitions are specified in a corresponding HMC inventory
# file.
#
# The format of HMC vault files is described in
# https://python-zhmcclient.readthedocs.io/en/master/development.html#hmc-vault-file

hmc_auth:

  HMC1:
    userid: ensadmin
    password: password
    verify: false

  HMC2:
    userid: ensadmin
    password_command: "my-get-otp {host}"
    password_timeout: 10
    verify: false

  HMC3:
    userid: ensadmin
    password_command: "my-get-vault -u {userid} -h {host}"
    password_timeout: 10
    verify: false

  MOCKED_Z16_CLASSIC:
    userid: dummy
    password: dummy

  MOCKED_Z16_DPM:
    userid: dummy
    password: dummy

The format of HMC vault files is compatible with the format of Ansible vault files in YAML format, with the following limitations:

  • In the current release, HMC vault files cannot be encrypted. To mitigate that, set restrictive file permissions on the HMC vault files.

8.6. Developing tests

The zhmcclient.testutils module provides support for developing tests that run against real HMCs or mocked HMCs defined with the Mock support.

These HMCs are defined in an HMC inventory file, and their credentials are defined in an HMC vault file.

8.6.1. zhmcclient.testutils module

zhmcclient.testutils - Utilities for testing against real or mocked HMCs.

This module defines pytest fixtures for use by the test functions and encapsulates the access to the HMC inventory and vault files.

Look at the existing test functions in https://github.com/zhmcclient/python-zhmcclient/tree/master/tests for real-life examples.

8.6.2. Pytest fixtures

Pytest fixtures are used as parameters of test functions. When used, they are specified just with their name. Pytest resolves the parameters of test functions to its known fixtures, based upon the parameter name. For more details on pytest fixtures in general, see pytest fixtures.

The ‘zhmcclient’ Python package provides a number of pytest fixtures that are useful for user-written test programs. They are also used by the end2end tests of the zhmcclient project itself. These fixtures are included in the ‘zhmcclient’ package as a pytest plugin, which enables them to be used by test programs without first having to import them. The pytest --fixtures command will display them along with a brief description.

The following pytest fixtures are provided. In their descriptions, the return value indicates what the fixture resolves to when used as a test function parameter:

zhmcclient.testutils.hmc_definition(request)[source]

Pytest fixture that provides an HMC definition from the HMC inventory file.

The HMC is selected via the TESTHMC environment variable when running pytest. If the selected HMC is a group in the HMC inventory file, the test function is called once for each HMC. For details, see Running end2end tests.

Returns:

The HMC definition from the HMC inventory file for the HMC to test against.

Return type:

HMCDefinition

zhmcclient.testutils.hmc_session(request, hmc_definition)[source]

Pytest fixture that provides a logged-on HMC session to an HMC defined in the HMC inventory file.

The HMC is selected via the TESTHMC environment variable when running pytest. If the selected HMC is a group in the HMC inventory file, the test function is called once for each HMC. For details, see Running end2end tests.

Upon fixture teardown, the session is logged off from the HMC.

This fixture has a scope of “session”, so the same HMC session is reused across all test modules for the complete pytest run.

This fixture is provided in the ‘zhmcclient’ Python package as a pytest plugin, so it is globally known to pytest and can be used without importing it.

Returns:

A logged-on session to the HMC to test against. The session object has an additional property named hmc_definition that is the HMCDefinition object for the corresponding HMC definition in the HMC inventory file.

Return type:

zhmcclient.Session or zhmcclient.mock.FakedSession

zhmcclient.testutils.all_cpcs(request, hmc_session)[source]

Pytest fixture that provides access to the CPCs to test against, regardless of their operational mode.

The CPCs to test against is defined in the cpcs variable in the HMC entry in the HMC inventory file; if that variable is omitted, it is the set of all managed CPCs.

The test function is invoked just once with the list of CPCs, and the test function needs to loop through the CPCs (or a subset).

The HMC is selected via the TESTHMC environment variable when running pytest. If the selected HMC is a group in the HMC inventory file, the test function is called once for each HMC. For details, see Running end2end tests.

This fixture has a scope of “session”, so the same HMC session is reused across all test modules for the complete pytest run.

This fixture is provided in the ‘zhmcclient’ Python package as a pytest plugin, so it is globally known to pytest and can be used without importing it.

Returns:

The CPCs to test against. These objects have the “short” set of properties from zhmcclient.Cpc.list().

Return type:

list of zhmcclient.Cpc

zhmcclient.testutils.dpm_mode_cpcs(request, hmc_session)[source]

Pytest fixture that provides access to the CPCs in DPM mode to test against.

The CPCs in DPM mode to test against is defined as list items in the cpcs variable in the HMC entry in the HMC inventory file, where the dpm_enabled property of the item is set to true.

The test function is invoked just once with the list of CPCs, and the test function needs to loop through the CPCs (or a subset).

The HMC is selected via the TESTHMC environment variable when running pytest. If the selected HMC is a group in the HMC inventory file, the test function is called once for each HMC. For details, see Running end2end tests.

This fixture has a scope of “session”, so the same HMC session is reused across all test modules for the complete pytest run.

This fixture is provided in the ‘zhmcclient’ Python package as a pytest plugin, so it is globally known to pytest and can be used without importing it.

Returns:

The CPCs in DPM mode to test against. These objects have the “short” set of properties from zhmcclient.Cpc.list().

Return type:

list of zhmcclient.Cpc

zhmcclient.testutils.classic_mode_cpcs(request, hmc_session)[source]

Pytest fixture that provides access to the CPCs in classic mode to test against.

The CPCs in classic mode to test against is defined as list items in the cpcs variable in the HMC entry in the HMC inventory file, where the dpm_enabled property of the item is omitted or set to false.

The test function is invoked just once with the list of CPCs, and the test function needs to loop through the CPCs (or a subset).

The HMC is selected via the TESTHMC environment variable when running pytest. If the selected HMC is a group in the HMC inventory file, the test function is called once for each HMC. For details, see Running end2end tests.

This fixture has a scope of “session”, so the same HMC session is reused across all test modules for the complete pytest run.

This fixture is provided in the ‘zhmcclient’ Python package as a pytest plugin, so it is globally known to pytest and can be used without importing it.

Returns:

The CPCs in classic mode to test against. These objects have the “short” set of properties from zhmcclient.Cpc.list().

Return type:

list of zhmcclient.Cpc

8.6.3. Encapsulation of HMC inventory file

The zhmcclient.testutils module provides the following elements to encapsulate access to the HMC inventory file, e.g. by test functions:

zhmcclient.testutils.hmc_definitions(load=True)[source]

Return the list of HMC definitions to be used for testing.

Parameters:

load (bool) – Load the HMC inventory and vault files. Otherwise, these files are not loaded. This is used to avoid a dependency on these files for normal zhmcclient users. If None, the ‘TESTEND2END_LOAD’ environment variable is used.

Returns:

list of zhmcclient.testutils.HMCDefinition

zhmcclient.testutils.print_hmc_definitions()[source]

Print all available HMC definitions in the HMC inventory and vault files.

class zhmcclient.testutils.HMCDefinitions(inventory_file=None, vault_file=None, testhmc=None, load=None)[source]

The HMC definitions in the HMC inventory file and their credentials in the HMC vault file.

Parameters:
  • inventory_file (string) – Path name of HMC inventory file`. If None, the file specified in the ‘TESTINVENTORY’ environment variable or if not set, the default file ~/.zhmc_inventory.yaml is used.

  • vault_file (string) – Path name of HMC vault file. If None, the file specified in the ‘TESTVAULT’ environment variable or if not set, the default file ~/.zhmc_vault.yaml is used.

  • testhmc (string) – Group nickname or HMC nickname in HMC inventory file to test against. If None, the nickname specified in the ‘TESTHMC’ environment variable or if not set, the nickname “default” is used.

  • load (bool) – Load the HMC inventory and vault files. Otherwise, these files are not loaded. This is used to avoid a dependency on these files for normal zhmcclient users. If None, the ‘TESTEND2END_LOAD’ environment variable is used.

Raises:

Methods:

__repr__()

Return repr(self).

list_hmcs([name])

Return a list of HMCDefinition objects in the HMC inventory file, for the specified HMC group or single HMC nickname.

list_all_hmcs()

List all HMCs in the HMC inventory file.

list_all_group_names()

List all group names in the HMC inventory file.

Attributes:

inventory_file

Path name of HMC inventory file.

vault_file

Path name of HMC vault file.

testhmc

HMC group or single HMC nickname to be tested.

group_names

The names of the HMC groups in the HMC inventory file.

__repr__()[source]

Return repr(self).

property inventory_file

Path name of HMC inventory file.

Type:

string

property vault_file

Path name of HMC vault file.

Type:

string

property testhmc

HMC group or single HMC nickname to be tested.

Type:

string

property group_names

The names of the HMC groups in the HMC inventory file.

Type:

list of string

list_hmcs(name=None)[source]

Return a list of HMCDefinition objects in the HMC inventory file, for the specified HMC group or single HMC nickname.

The path names in the HMCDefinition.mock_file property are absolute path names, whereby any relative path names in the HMC inventory file have been interpreted relative to the directory of the HMC inventory file.

Parameters:

name (string) – Name of an HMC group or nickname of a single HMC in the HMC inventory file. If None, the default group or nickname defined in HMCDefinitions.testhmc is used.

Returns:

The specified HMCs in the HMC

inventory file.

Return type:

list of HMCDefinition

Raises:

zhmcclient.testutils.HMCNotFound – HMC group or nickname not found.

list_all_hmcs()[source]

List all HMCs in the HMC inventory file.

Returns:

All HMCs in the HMC inventory file.

Return type:

list of HMCDefinition

list_all_group_names()[source]

List all group names in the HMC inventory file.

Returns:

All group names in the HMC inventory file.

Return type:

list of string

class zhmcclient.testutils.HMCDefinition(nickname, description='', contact='', access_via='', mock_file=None, host=None, userid=None, password=None, password_command=None, password_timeout=None, verify=True, ca_certs=None, cpcs=None, add_vars=None)[source]

A single HMC definition.

An HMC definition contains information needed to use the WS API of a real HMC or to setup and use a mocked HMC, some organizational information about the HMC, and some information about the CPCs managed by the HMC that are to be tested. It can also contain arbitrary additional variables.

Parameters:
  • nickname (string) – Nickname of the HMC (DNS name, IP address, or host alias).

  • description (string) – Short description of the HMC.

  • contact (string) – Name of the technical contact of the HMC.

  • access_via (string) – Networking preconditions for reaching the HMC.

  • mock_file (string) – Path name of HMC mock file, or None. This argument is used to detect whether the HMC is a real or mocked HMC: If None, it is a real HMC. Otherwise, it is a mocked HMC and the path name is stored as provided.

  • host (string or list of string) – IP address or DNS hostname of the real HMC or list of redundant HMCs. Required for real HMCs, must not be None. Optional for mocked HMCs.

  • userid (string) – Userid (username) for authenticating with the HMC. Required, must not be None.

  • password (string) – Password for authenticating with the HMC. Mutually exclusive with ‘password_command’; One of them is required and must not be None.

  • password_command (string) – Password command that obtains a password for authenticating with the HMC. Mutually exclusive with ‘password’; One of them is required and must not be None.

  • password_timeout (int) – Timeout for the password command, in seconds.

  • verify (bool) – Verify the HMC certificate as specified in ca_certs. Optional, defaults to True.

  • ca_certs (string) – Path name of certificate file or certificate directory to be used for verifying the HMC certificate, or None. If None, the path name in the ‘REQUESTS_CA_BUNDLE’ environment variable, or the path name in the ‘CURL_CA_BUNDLE’ environment variable, or the certificates in the Mozilla CA Certificate List provided by the ‘certifi’ Python package are used. Optional, defaults to None.

  • cpcs (dict) –

    CPCs managed by the HMC that are to be tested. If None, all managed CPCs are tested.

    • key: CPC name.

    • value: dict of expected CPC properties, using underscored property names. Used for basic classification of the CPC, e.g. ‘dpm-mode’, ‘machine-type’, ‘machine-model’.

  • add_vars (dict) – Additional variables. The variable values can have arbitrary types.

Methods:

__repr__()

Return repr(self).

Attributes:

nickname

Nickname of the HMC (exists only in this encapsulation class, not known by the HMC itself).

description

Short description of the HMC.

contact

Name of the technical contact of the HMC.

access_via

Networking preconditions for reaching the HMC.

mock_file

Path name of HMC mock file, or None.

host

IP address or DNS hostname of the HMC or list of redundant HMCs.

userid

Userid (username) for authenticating with the HMC.

password

Password for authenticating with the HMC.

password_command

Command for obtaining a password for authenticating with the HMC.

password_timeout

Timeout for the password command, in seconds.

verify

Verify the HMC certificate as specified in ca_certs.

ca_certs

Path name of certificate file or certificate directory to be used for verifying the HMC certificate, or None.

verify_cert

A combination of verify and ca_certs for direct use as the verify_cert parameter of zhmcclient.Session.

cpcs

CPCs managed by the HMC that are to be tested.

add_vars

Additional variables for the HMC definition.

__repr__()[source]

Return repr(self).

property nickname

Nickname of the HMC (exists only in this encapsulation class, not known by the HMC itself).

Type:

string

property description

Short description of the HMC.

Type:

string

property contact

Name of the technical contact of the HMC.

Type:

string

property access_via

Networking preconditions for reaching the HMC.

For example, Boundary firewall or VPN connection.

Type:

string

property mock_file

Path name of HMC mock file, or None.

An HMC mock file defines a mocked HMC based on the zhmcclient.mock support.

This property indicates whether the HMC is a real or mocked HMC: If None, it is a real HMC, otherwise it is a mocked HMC.

Type:

string

property host

IP address or DNS hostname of the HMC or list of redundant HMCs.

This is a settable property.

Type:

string or list of string

property userid

Userid (username) for authenticating with the HMC.

Type:

string

property password

Password for authenticating with the HMC.

Type:

string

property password_command

Command for obtaining a password for authenticating with the HMC.

Type:

string

property password_timeout

Timeout for the password command, in seconds.

Type:

string

property verify

Verify the HMC certificate as specified in ca_certs.

Type:

bool

property ca_certs

Path name of certificate file or certificate directory to be used for verifying the HMC certificate, or None.

If None, the path name in the ‘REQUESTS_CA_BUNDLE’ environment variable, or the path name in the ‘CURL_CA_BUNDLE’ environment variable, or the certificates in the Mozilla CA Certificate List provided by the ‘certifi’ Python package are used.

Type:

string

property verify_cert

A combination of verify and ca_certs for direct use as the verify_cert parameter of zhmcclient.Session.

Type:

bool or string

property cpcs

CPCs managed by the HMC that are to be tested. If None, all managed CPCs are tested.

Each dict item represents one CPC:

  • key (string): CPC name.

  • value (dict): Dict with expected CPC properties (with underscores).

Type:

dict

property add_vars

Additional variables for the HMC definition.

Each dict item represents one variable:

  • key (string): Variable name.

  • value (object): Variable value.

Type:

dict

class zhmcclient.testutils.HMCInventoryFile(filepath)[source]

Encapsulation of an HMC inventory file in YAML format.

Attributes:

filepath

Path name of the HMC inventory file.

data

Content of the HMC inventory file, as nested dict and list objects.

property filepath

Path name of the HMC inventory file.

Type:

string

property data

Content of the HMC inventory file, as nested dict and list objects.

Type:

dict

8.6.4. Encapsulation of HMC vault file

The zhmcclient.testutils module provides the following elements to encapsulate access to the HMC vault file, e.g. by test functions:

class zhmcclient.testutils.HMCVaultFile(filepath)[source]

Encapsulation of an HMC vault file in YAML format.

Parameters:

filepath (str) – Path name of HMC vault file.

Raises:

HMCVaultFileError – An error in the HMC vault file

Attributes:

filepath

Path name of the HMC vault file.

data

Content of the HMC vault file, as nested dict and list objects.

property filepath

Path name of the HMC vault file.

Type:

string

property data

Content of the HMC vault file, as nested dict and list objects.

Type:

dict

8.6.5. Helper functions for HMC session management

The zhmcclient.testutils module provides the following functions and attributes for managing HMC sessions. These functions are used by the testutils classes and can also be used for tests of other projects that use zhmcclient:

zhmcclient.testutils.setup_hmc_session(hd, rt_config=None, skip_on_failure=True)[source]

Setup an HMC session and return a new session object for it.

If the HMC definition represents a real HMC, log on to an HMC and return a new zhmcclient.Session object.

If the HMC definition represents a mocked HMC, create a new mock environment from that and return a zhmcclient.mock.FakedSession object.

Parameters:
  • hd (HMCDefinition) – The HMC definition of the HMC the test runs against.

  • rt_config (RetryTimeoutConfig) – Retry / timeout configuration. If None, a default is used.

  • skip_on_failure (bool) – If the HMC logon fails, invoke pytest.skip() instead of raising exceptions.

Returns:

Session object for the logged-on real or mocked session with the HMC.

Return type:

Session)

Raises:
  • zhmcclient.PasswordCommandFailure – Password command failed

  • zhmcclient.ConnectionError – Cannot connect to the HMC (only for skip_on_failure=False)

  • zhmcclient.AuthError – Cannot authenticate with the HMC (only for skip_on_failure=False)

  • zhmcclient.HTTPError – Other HTTP error with the HMC (only for skip_on_failure=False)

zhmcclient.testutils.teardown_hmc_session(session)[source]

Log off from a valid session with a real HMC, identified by a zhmcclient session object.

If the session represents a mocked HMC, nothing is done.

Parameters:

session (Session) – Session with a real or mocked HMC.

zhmcclient.testutils.teardown_hmc_session_id(hd, session_id)[source]

Log off from a valid session with a real HMC, identified by its session ID.

If the HMC definition represents a mocked HMC, nothing is done.

Raises zhmcclient exceptions if the session ID is not valid.

Parameters:
  • hd (HMCDefinition) – The HMC definition of the HMC the test runs against.

  • session_id (str) – HMC session ID.

zhmcclient.testutils.is_valid_hmc_session_id(hd, session_id)[source]

Return a boolean indicating whether an HMC session ID is valid.

If the HMC definition represents a real HMC, the specified session ID is tested with an HMC operation.

If the HMC definition represents a mocked HMC, no such test is performed, and the specified session ID is considered valid if it is None.

Raises zhmcclient exceptions if the validity cannot be determined.

Parameters:
  • hd (HMCDefinition) – The HMC definition of the HMC the test runs against.

  • session_id (str) – HMC session ID to be tested for validity.

The following attributes are used when test logging is enabled. For details, see Enabling logging during end2end tests:

zhmcclient.testutils.LOG_FORMAT_STRING

Log format for test logging.

zhmcclient.testutils.LOG_DATETIME_FORMAT

Datetime format for test logging.

zhmcclient.testutils.LOG_DATETIME_TIMEZONE

Timezone used for datetime values in test logging.

8.6.6. Exceptions

The zhmcclient.testutils module may raise the following exceptions:

class zhmcclient.testutils.HMCInventoryFileError[source]

An error in the HMC inventory file.

class zhmcclient.testutils.HMCVaultFileError[source]

An error in the HMC vault file.

class zhmcclient.testutils.HMCNoVaultError[source]

The HMC vault file does not have a corresponding entry for the HMC.

class zhmcclient.testutils.HMCNotFound[source]

The HMC group or nickname was not found in the HMC inventory file.

8.7. Contributing

Third party contributions to this project are welcome!

In order to contribute, create a Git pull request, considering this:

  • Test is required.

  • Each commit should only contain one “logical” change.

  • A “logical” change should be put into one commit, and not split over multiple commits.

  • Large new features should be split into stages.

  • The commit message should not only summarize what you have done, but explain why the change is useful.

  • The commit message must follow the format explained below.

What comprises a “logical” change is subject to sound judgement. Sometimes, it makes sense to produce a set of commits for a feature (even if not large). For example, a first commit may introduce a (presumably) compatible API change without exploitation of that feature. With only this commit applied, it should be demonstrable that everything is still working as before. The next commit may be the exploitation of the feature in other components.

For further discussion of good and bad practices regarding commits, see:

8.8. Making a change

To make a change, create a topic branch. You can assume that you are the only one using that branch, so force-pushes to that branch and rebasing that branch is fine.

When you are ready to push your change, describe the change for users of the package in a change fragment file. To create a change fragment file, execute:

For changes that have a corresponding issue:

towncrier create <issue>.<type>.rst --edit

For changes that have no corresponding issue:

towncrier create noissue.<number>.<type>.rst --edit

For changes where you do not want to create or modify a change log entry, simply don’t provide a change fragment file.

where:

  • <issue> - The issue number of the issue that is addressed by the change. If the change addresses more than one issue, copy the new change fragment file after its content has been edited, using the other issue number in the file name. It is important that the file content is exactly the same, so that towncrier can create a single change log entry from the two (or more) files.

    If the change has no related issue, use the noissue.<number>.<type>.rst file name format, where <number> is any number that results in a file name that does not yet exist in the changes directory.

  • <type> - The type of the change, using one of the following values:

    • incompatible - An incompatible change. This will show up in the “Incompatible Changes” section of the change log. The text should include a description of the incompatibility from a user perspective and if possible, how to mitigate the change or what replacement functionality can be used instead.

    • deprecation - An externally visible functionality is being deprecated in this release. This will show up in the “Deprecations” section of the change log. The deprecated functionality still works in this release, but may go away in a future release. If there is a replacement functionality, the text should mention it.

    • fix - A bug fix in the code, documentation or development environment. This will show up in the “Bug fixes” section of the change log.

    • feature - A feature or enhancement in the code, documentation or development environment. This will show up in the “Enhancements” section of the change log.

    • cleanup - A cleanup in the code, documentation or development environment, that does not fix a bug and is not an enhanced functionality. This will show up in the “Cleanup” section of the change log.

This command will create a new change fragment file in the changes directory and will bring up your editor (usually vim).

If your change does multiple things of different types listed above, create a separate change fragment file for each type.

If you need to modify an existing change log entry as part of your change, edit the existing corresponding change fragment file.

Add the new or changed change fragment file(s) to your commit. The test workflow running on your Pull Request will check whether your change adds or modifies change fragment files.

You can review how your changes will show up in the final change log for the upcoming release by running:

towncrier build --draft

Always make sure that your pushed branch has either just one commit, or if you do multiple things, one commit for each logical change. What is not OK is to keep the possibly multiple commits it took you to get to the final result for the change.

8.9. Format of commit messages

A commit message must start with a short summary line, followed by a blank line.

Optionally, the summary line may start with an identifier that helps identifying the type of change or the component that is affected, followed by a colon.

It can include a more detailed description after the summary line. This is where you explain why the change was done, and summarize what was done.

It must end with the DCO (Developer Certificate of Origin) sign-off line in the format shown in the example below, using your name and a valid email address of yours. The DCO sign-off line certifies that you followed the rules stated in DCO 1.1. In short, you certify that you wrote the patch or otherwise have the right to pass it on as an open-source patch.

All lines in the commit messages must not be longer than 80 characters.

We check in the test workflow whether the commit messages in the pull request comply to this format. If the commit messages do not comply, the test workflow will fail.

Example commit message:

cookies: Add support for delivering cookies

Cookies are important for many people. This change adds a pluggable API for
delivering cookies to the user, and provides a default implementation.

Signed-off-by: Random J Developer <random@developer.org>

Use git commit --amend to edit the commit message, if you need to.

Use the --signoff (-s) option of git commit to append a sign-off line to the commit message with your name and email as known by Git.

If you like filling out the commit message in an editor instead of using the -m option of git commit, you can automate the presence of the sign-off line by using a commit template file:

  • Create a file outside of the repo (say, ~/.git-signoff.template) that contains, for example:

    <one-line subject>
    
    <detailed description>
    
    Signed-off-by: Random J Developer <random@developer.org>
    
  • Configure Git to use that file as a commit template for your repo:

    git config commit.template ~/.git-signoff.template
    

8.10. Handling Dependabot alerts and PRs

The GitHub Dependabot settings on this repo are set as follows:

  • Dependabot alerts: Enabled

  • Dependabot malware alerts: Enabled

  • Dependabot security updates: Enabled

This causes the creation of Dependabot alerts and the creation of Dependabot pull requests to fix them.

These pull requests can be recognized by their dependencies label. They increase the package versions in the requirements files and also in the minimum-constraints files. However, there are some limitations:

  • When a new package version cannot by installed in all supported Python environments, Dependabot adds an according warning to the alert, and does not create a fix PR. The warning in the alert reads like this:

    ` Dependabot cannot update <package> to a non-vulnerable version `

  • Dependabot does not always correctly handle environment markers in requirements and minimum-constraints files.

Dependabot alerts should be handled as follows:

  • For created PRs, double check that all occurrences of the package have been increased in the *.txt files and that the PR succeedes.

    Then, add the backport label and merge the PR.

    The presence of the backport label will cause a backport PR to the latest stable_M.N branch to be created. See Backporting for details. Merging the PR will close the Dependabot alert(s).

  • For the remaining Dependabot alerts, create PRs that increase the package version to the version that is recommended in the PR. Make sure you do that for all occurrences of the package in the *.txt files. You probably will need to split the entry for the package by Python version. Use Pypi to find out which package versions support which Python versions.

    Example:

    Assume this package requires Python >=3.9 and the minimum-constraints-install.txt file contains a single entry for the urllib3 package (it would also be in requirements.txt with >=):

    urllib3==2.6.0
    

    Dependabot has an alert that recommends upgrading urllib3 to 2.7.0, but has failed creating a PR.

    The urllib3 package on Pypi shows that version 2.6.3 is the latest version supported on Python 3.9, and version 2.7.0 requires Python 3.10.

    Split the entry between these two Python versions:

    urllib3==2.6.0; python_version == '3.9'
    urllib3==2.7.0; python_version >= '3.10'
    

8.11. Backporting

This repo supports assisted backporting of PRs targeting the master branch to the latest stable_M.N branch.

To trigger the backporting, add the label backport to a PR targeting the master branch. Merging that PR will cause a backport PR to be created, if the backporting can be done without merge conflicts.

This is done by the backport.yml GitHub Actions workflow. The workflow determines the latest version of existing stable_M.N branches and then attempts to cherry-pick the PR to that branch. If there are merge conflicts, the workflow fails.

When merging the PR with the backport label does not create a backport PR, look at the run of the backport workflow to find out why it failed and create the backport PR by cherry-picking the commits from the original PR and resolving the merge conflicts. For this, it is helpful to have only one commit in each PR.

8.12. Releasing a version

This section shows the steps for releasing a version to PyPI.

It covers all variants of versions that can be released:

  • Releasing a new major version (Mnew.0.0) based on the master branch

  • Releasing a new minor version (M.Nnew.0) based on the master branch or based on an earlier stable branch

  • Releasing a new update version (M.N.Unew) based on the stable branch of its minor version

This description assumes that you are authorized to push to the remote repo at https://github.com/zhmcclient/python-zhmcclient and that the remote repo has the remote name origin in your local clone.

Any commands in the following steps are executed in the main directory of your local clone of the python-zhmcclient Git repo.

  1. On GitHub, verify open items in milestone M.N.U.

    Verify that milestone M.N.U has no open issues or PRs anymore. If there are open PRs or open issues, make a decision for each of those whether or not it should go into version M.N.U you are about to release.

    If there are open issues or PRs that should go into this version, abandon the release process.

    If none of the open issues or PRs should go into this version, change their milestones to a future version, and proceed with the release process. You may need to create the milestone for the future version.

  2. Run the Safety tool:

    make safety
    

    If any of the two safety runs fails, fix the safety issues that are reported, in a separate branch/PR.

    Backport the PR into the latest stable_M.N branch.

  3. Run the check for missing dependencies:

    make check_reqs
    

    If this fails, add the missing dependencies that are reported to the correct minimum-constraints*.txt file, in a separate branch/PR.

    You can determine the correct minimum-constraints*.txt file for a dependent package by using python -m pipdeptree -r -p <package-name> to see which other packages use it. The dependent package should be put into the minimum-constraints*.txt file that has the package(s) using it.

    Backport the PR into the latest stable_M.N branch.

  4. Check for any Dependabot alerts and Dependabot PRs.

    If there are any Dependabot alerts or PRs, fix them as described in Handling Dependabot alerts and PRs.

  5. Check for any Mend issues

    1. Push the master branch to the internal repo to bring it in sync with the public repo. This only makes a change for Mend if the pip requirements or constraints files have changed, but we do it always:

      git checkout master
      git pull
      git push ibmfork master
      
    2. Process any Mend issues in the internal repo.

      If there are any Mend issues in the internal issue tracker, fix them in a separate PR or PRs.

      Backport the PR(s) into the latest stable_M.N branch.

  6. Create and push the release branch (replace M,N,U accordingly):

    VERSION=M.N.U make release_branch
    

    This uses the default branch determined from VERSION: For M.N.0, the master branch is used, otherwise the stable_M.N branch is used. That covers for all cases except if you want to release a new minor version based on an earlier stable branch. In that case, you need to specify that branch:

    VERSION=M.N.0 BRANCH=stable_M.N make release_branch
    

    This includes the following steps:

    • create the release branch (release_M.N.U), if not yet existing

    • make sure the AUTHORS.md file is up to date

    • update the change log from the change fragment files, and delete those

    • commit the changes to the release branch

    • push the release branch

    If this command fails, the fix can be committed to the release branch and the command above can be retried.

  7. On GitHub, create a Pull Request for the release branch release_M.N.U.

    Important: GitHub uses master as the default target branch. When releasing based on a stable branch, you need to change the target branch to the intended stable_M.N branch.

    Set the milestone of that PR to version M.N.U.

    This PR should normally be set to be reviewed by at least one of the maintainers.

    The PR creation will cause the “test” workflow to run. That workflow runs tests for all defined environments, since it discovers by the branch name that this is a PR for a release.

  8. On GitHub, once the checks for that Pull Request have succeeded, merge the Pull Request (no review is needed). This automatically deletes the branch on GitHub.

    If the PR did not succeed, fix the issues.

  9. On GitHub, close milestone M.N.U.

    Verify that the milestone has no open items anymore. If it does have open items, investigate why and fix (probably step 1 was not performed).

  10. Publish the package (replace M,N,U accordingly):

    VERSION=M.N.U make release_publish
    

    or (see step 4):

    VERSION=M.N.0 BRANCH=stable_M.N make release_publish
    

    This includes the following steps:

    • create and push the release tag

    • clean up the release branch

    Pushing the release tag will cause the “publish” workflow to run. That workflow builds the package, publishes it on PyPI, creates a release for it on GitHub, and finally creates a new stable branch on GitHub if the master branch was released.

  11. Verify the publishing

    Wait for the “publish” workflow for the new release to have completed: https://github.com/zhmcclient/python-zhmcclient/actions/workflows/publish.yml

    Then, perform the following verifications:

  12. Verify the documentation on ReadTheDocs

    ReadTheDocs automatically activates the new version and sets it as a default version. Branches such as ‘master’ or ‘stable’ are no longer shown.

    Wait for the ReadTheDocs build for the new version to have completed: https://readthedocs.org/projects/python-zhmcclient/builds/

    Then, perform the following verification:

  13. Hide previous fix version on ReadTheDocs

    When releasing a fix version != 0 (e.g. M.N.1), log on to https://readthedocs.org/accounts/login/, go to https://readthedocs.org/projects/python-zhmcclient/versions/, select to configure the previous fix version (i.e. M.N.U-1) and set it to “hidden” (it remains active).

    Hiding it causes it to be removed from the version list. Keeping it active will ensure that any links to that version that were obtained earlier, still work.

8.13. Starting a new version

This section shows the steps for starting development of a new version.

This section covers all variants of new versions:

  • Starting a new major version (Mnew.0.0) based on the master branch

  • Starting a new minor version (M.Nnew.0) based on the master branch or based on an earlier stable branch

  • Starting a new update version (M.N.Unew) based on the stable branch of its minor version

This description assumes that you are authorized to push to the remote repo at https://github.com/zhmcclient/python-zhmcclient and that the remote repo has the remote name origin in your local clone.

Any commands in the following steps are executed in the main directory of your local clone of the python-zhmcclient Git repo.

  1. Create and push the start branch (replace M,N,U accordingly):

    VERSION=M.N.U make start_branch
    

    This uses the default branch determined from VERSION: For M.N.0, the master branch is used, otherwise the stable_M.N branch is used. That covers for all cases except if you want to start a new minor version based on an earlier stable branch. In that case, you need to specify that branch:

    VERSION=M.N.0 BRANCH=stable_M.N make start_branch
    

    This includes the following steps:

    • create the start branch (start_M.N.U), if not yet existing

    • create a dummy change

    • commit and push the start branch (start_M.N.U)

  2. On GitHub, create a milestone for the new version M.N.U.

    You can create a milestone in GitHub via Issues -> Milestones -> New Milestone.

  3. On GitHub, create a Pull Request for the start branch start_M.N.U.

    Important: GitHub uses master as the default target branch. When releasing based on a stable branch, you need to change the target branch to the intended stable_M.N branch.

    No review is needed for this PR.

    Set the milestone of that PR to the new version M.N.U.

  4. On GitHub, go through all open issues and pull requests that still have milestones for previous releases set, and either set them to the new milestone, or to have no milestone.

    Note that when the release process has been performed as described, there should not be any such issues or pull requests anymore. So this step here is just an additional safeguard.

  5. On GitHub, once the checks for the Pull Request for branch start_M.N.U have succeeded, merge the Pull Request (no review is needed). This automatically deletes the branch on GitHub.

  6. Update and clean up the local repo (replace M,N,U accordingly):

    VERSION=M.N.U make start_tag
    

    or (see step 1):

    VERSION=M.N.0 BRANCH=stable_M.N make start_tag
    

    This includes the following steps:

    • checkout and pull the branch that was started (master or stable_M.N)

    • delete the start branch (start_M.N.U) locally and remotely

    • create and push the start tag (M.N.Ua0)

8.14. Checks when making a release

This section describes which tests and checks are run when the zhmcclient package is released to Pypi. All these checks must pass in order to make the release.

The following tests are run automatically by GitHub Actions on all supported combinations of operating system, Python version and minimum/latest package levels:

In addition, the following tests are run manually: