tmt.container package

Module contents

Container decorators and helpers.

tmt.container.ContainerClass

Types for generic “data container” classes and instances. In tmt code, this reduces to data classes and data class instances. Our DataContainer are perfectly compatible data classes, but some helper methods may be used on raw data classes, not just on DataContainer instances.

alias of type[DataclassInstance]

class tmt.container.DataContainer

Bases: object

A base class for objects that have keys and values

property is_bare: bool

Check whether all keys are either unset or have their default value.

Returns:

True if all keys either hold their default value or are not set at all, False otherwise.

items() Iterator[tuple[str, Any]]

Iterate over key/value pairs

classmethod keys() Iterator[str]

Iterate over key names

to_dict() dict[str, Any]

Convert to a mapping.

See https://tmt.readthedocs.io/en/stable/code/classes.html#class-conversions for more details.

to_minimal_dict() dict[str, Any]

Convert to a mapping with unset keys omitted.

See https://tmt.readthedocs.io/en/stable/code/classes.html#class-conversions for more details.

values() Iterator[Any]

Iterate over key values

tmt.container.FieldCLIOption: TypeAlias = str | collections.abc.Sequence[str]

Type of field’s CLI option specification.

tmt.container.FieldExporter

Type of field’s exporter callback.

alias of Callable[[T], Any]

class tmt.container.FieldMetadata(internal: bool = False, help: str | None = None, help_example_values: list[str] = <factory>, _metavar: str | None = None, default: ~tmt.container.T | None = None, default_factory: ~typing.Callable[[], ~tmt.container.T] | None = None, is_flag: bool = False, multiple: bool = False, show_default: bool = False, _choices: None | ~collections.abc.Sequence[str] | ~typing.Callable[[], ~collections.abc.Sequence[str]] = None, envvar: str | None = None, deprecated: tmt.options.Deprecated | None = None, cli_option: str | ~collections.abc.Sequence[str] | None = None, normalize_callback: NormalizeCallback[T] | None = None, serialize_callback: SerializeCallback[T] | None = None, unserialize_callback: SerializeCallback[T] | None = None, export_callback: FieldExporter[T] | None = None, _option_args: FieldCLIOption | None = None, _option_kwargs: dict[str, ~typing.Any] = <factory>, _option: tmt.options.ClickOptionDecoratorType | None = None)

Bases: Generic[T]

A dataclass metadata container used by our custom dataclass field management.

Attached to fields defined with field()

property choices: Sequence[str] | None

A list of allowed values the field can take

cli_option: str | Sequence[str] | None = None

One or more command-line option names.

default: T | None = None

The default value for the field.

default_factory: Callable[[], T] | None = None

A zero-argument callable that will be called when a default value is needed for the field.

deprecated: tmt.options.Deprecated | None = None

Mark the option as deprecated. Instance of Deprecated describes the version in which the field was deprecated plus an optional hint with the recommended alternative. Documentation and help texts would contain this info.

envvar: str | None = None

Environment variable providing value for the field.

export_callback: FieldExporter[T] | None = None

An export callback to call when exporting the field (performed by tmt.export.Exportable).

property has_default: bool

Whether the field has a default value

help: str | None = None

Help text documenting the field.

help_example_values: list[str]

Specific values that should be shown in the documentation as interesting examples of the field usage.

internal: bool = False
is_flag: bool = False

Marks the fields as a flag.

property materialized_default: T | None

Returns the actual default value of the field

property metavar: str | None

Placeholder for field’s value in documentation and help

multiple: bool = False

Marks the field as accepting multiple values. When used on command line, the option could be used multiple times, accumulating values.

normalize_callback: NormalizeCallback[T] | None = None

A normalization callback to call when loading the value from key source (performed by NormalizeKeysMixin).

property option: tmt.options.ClickOptionDecoratorType | None
serialize_callback: SerializeCallback[T] | None = None
show_default: bool = False

If set, show the default value in command line help.

unserialize_callback: SerializeCallback[T] | None = None
class tmt.container.MetadataContainer

Bases: BaseModel

A base class of containers backed by fmf nodes.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

classmethod from_fmf(tree: Tree) Self
classmethod from_json(json_data: str) Self
classmethod from_yaml(yaml: str) Self
model_config: ClassVar[ConfigDict] = {'alias_generator': <function key_to_option>, 'extra': 'forbid', 'validate_assignment': True, 'validate_default': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tmt.container.MetadataContainerT

A typevar bound to spec-based container base class. A stand-in for all classes derived from SpecBasedContainer.

alias of TypeVar(‘MetadataContainerT’, bound=MetadataContainer)

tmt.container.NormalizeCallback

Type of field’s normalization callback.

alias of Callable[[str, Any, tmt.log.Logger], T]

class tmt.container.SerializableContainer

Bases: DataContainer

A mixin class for saving and loading objects

classmethod default(key: str, default: Any = None) Any
classmethod extract_from(obj: Any) Self

Extract keys from given object, and save them in a container

classmethod from_serialized(serialized: dict[str, Any]) Self

Convert from a serialized form loaded from a file.

See https://tmt.readthedocs.io/en/stable/code/classes.html#class-conversions for more details.

See to_serialized() for its counterpart.

inject_to(obj: Any) None

Inject keys from this container into attributes of a given object

to_serialized() dict[str, Any]

Convert to a form suitable for saving in a file.

See https://tmt.readthedocs.io/en/stable/code/classes.html#class-conversions for more details.

See from_serialized() for its counterpart.

static unserialize(serialized: dict[str, Any], logger: tmt.log.Logger) SerializableContainerDerivedType

Convert from a serialized form loaded from a file.

Similar to from_serialized(), but this method knows nothing about container’s class, and will locate the correct module and class by inspecting serialized data. Discovered class’ from_serialized() is then used to create the container.

Used to transform data read from a YAML file into original containers when their classes are not know to the code. Restoring such containers requires inspection of serialized data and dynamic imports of modules as needed.

See https://tmt.readthedocs.io/en/stable/code/classes.html#class-conversions for more details.

See to_serialized() for its counterpart.

classmethod unserialize_class() Any

Provide the actual class to unserialize.

In some situations, the class recorded in the serialized state cannot be safely unserialized. Such classes may reimplement this method, and return the right class.

tmt.container.SerializeCallback

Type of field’s serialization callback.

alias of Callable[[T], Any]

class tmt.container.SpecBasedContainer

Bases: Generic[SpecInT, SpecOutT], DataContainer, ABC

abstractmethod classmethod from_spec(spec: SpecInT) Self

Convert from a specification file or from a CLI option

See https://tmt.readthedocs.io/en/stable/code/classes.html#class-conversions for more details.

See to_spec() for its counterpart.

to_minimal_spec() SpecOutT

Convert to specification, skip default values

See https://tmt.readthedocs.io/en/stable/code/classes.html#class-conversions for more details.

See from_spec() for its counterpart.

to_spec() SpecOutT

Convert to a form suitable for saving in a specification file

See https://tmt.readthedocs.io/en/stable/code/classes.html#class-conversions for more details.

See from_spec() for its counterpart.

class tmt.container.SpecBasedContainerT

A typevar bound to spec-based container base class. A stand-in for all classes derived from SpecBasedContainer.

alias of TypeVar(‘SpecBasedContainerT’, bound=SpecBasedContainer)

class tmt.container.SpecInT

A typevar representing an input specification consumed by SpecBasedContainer.

alias of TypeVar(‘SpecInT’)

class tmt.container.SpecOutT

A typevar representing an output specification produced by SpecBasedContainer.

alias of TypeVar(‘SpecOutT’)

tmt.container.UnserializeCallback

Type of field’s unserialization callback.

alias of Callable[[Any], T]

tmt.container.container_field(container: type[DataclassInstance] | DataclassInstance, key: str) tuple[str, str, Any, Field[Any], FieldMetadata[Any]]

Return a dataclass/data container field info by the field’s name.

Surprisingly, dataclasses package does not have a helper for this. One can iterate over fields, but there’s no public API for retrieving a field when one knows its name.

Parameters:
  • cls – a dataclass/data container class whose fields to search.

  • key – field name to retrieve.

Raises:

GeneralError – when the field does not exist.

tmt.container.container_fields(container: type[DataclassInstance] | DataclassInstance) Iterator[Field[Any]]
tmt.container.container_has_field(container: type[DataclassInstance] | DataclassInstance, key: str) bool
tmt.container.container_items(container: DataclassInstance) Iterator[tuple[str, Any]]

Iterate over key/value pairs in a container

tmt.container.container_keys(container: type[DataclassInstance] | DataclassInstance) Iterator[str]

Iterate over key names in a container

tmt.container.container_values(container: DataclassInstance) Iterator[Any]

Iterate over values in a container

tmt.container.field(*, default: bool, option: str | Sequence[str] | None = None, is_flag: bool = True, choices: None | Sequence[str] | Callable[[], Sequence[str]] = None, multiple: bool = False, metavar: str | None = None, envvar: str | None = None, deprecated: 'tmt.options.Deprecated' | None = None, help: str | None = None, help_example_values: list[str] | None = None, show_default: bool = False, internal: bool = False) bool
tmt.container.field(*, default: T, option: str | Sequence[str] | None = None, is_flag: bool = False, choices: None | Sequence[str] | Callable[[], Sequence[str]] = None, multiple: bool = False, metavar: str | None = None, envvar: str | None = None, deprecated: 'tmt.options.Deprecated' | None = None, help: str | None = None, help_example_values: list[str] | None = None, show_default: bool = False, internal: bool = False, normalize: NormalizeCallback[T] | None = None, serialize: Callable[[T], Any] | None = None, unserialize: Callable[[Any], T] | None = None, exporter: Callable[[T], Any] | None = None) T
tmt.container.field(*, default_factory: Callable[[], T], option: str | Sequence[str] | None = None, is_flag: bool = False, choices: None | Sequence[str] | Callable[[], Sequence[str]] = None, multiple: bool = False, metavar: str | None = None, envvar: str | None = None, deprecated: 'tmt.options.Deprecated' | None = None, help: str | None = None, help_example_values: list[str] | None = None, show_default: bool = False, internal: bool = False, normalize: NormalizeCallback[T] | None = None, serialize: Callable[[T], Any] | None = None, unserialize: Callable[[Any], T] | None = None, exporter: Callable[[T], Any] | None = None) T
tmt.container.field(*, option: str | Sequence[str] | None = None, is_flag: bool = False, choices: None | Sequence[str] | Callable[[], Sequence[str]] = None, multiple: bool = False, metavar: str | None = None, envvar: str | None = None, deprecated: 'tmt.options.Deprecated' | None = None, help: str | None = None, help_example_values: list[str] | None = None, show_default: bool = False, internal: bool = False, normalize: NormalizeCallback[T] | None = None, serialize: Callable[[T], Any] | None = None, unserialize: Callable[[Any], T] | None = None, exporter: Callable[[T], Any] | None = None) T

Define a DataContainer field.

Effectively a fancy wrapper over dataclasses.field(), tailored for tmt code needs and simplification of various common tasks.

Parameters:
  • default – if provided, this will be the default value for this field. Passed directly to dataclass.field(). It is an error to specify both default and default_factory.

  • default_factory – if provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Passed directly to dataclass.field(). It is an error to specify both default and default_factory.

  • option – one or more command-line option names. Passed directly to click.option().

  • is_flag – marks this option as a flag. Passed directly to click.option().

  • choices – if provided, the command-line option would accept only the listed input values. Passed to click.option() as a click.Choice instance.

  • multiple – accept multiple arguments of the same name. Passed directly to click.option().

  • metavar – how the input value is represented in the help page. Passed directly to click.option().

  • envvar – environment variable used for this option. Passed directly to click.option().

  • deprecated – mark the option as deprecated Provide an instance of Deprecated() with version in which the option was obsoleted and an optional hint with the recommended alternative. A warning message will be added to the option help.

  • help – the help string for the command-line option. Multiline strings can be used, textwrap.dedent() is applied before passing help to click.option().

  • help_example_values – Specific values that should be shown in the documentation as interesting examples of the field usage.

  • show_default – show default value Passed directly to click.option().

  • internal – if set, the field is treated as internal-only, and will not appear when showing objects via show() method, or in export created by Core._export().

  • normalize – a callback for normalizing the input value. Consumed by NormalizeKeysMixin.

  • serialize – a callback for custom serialization of the field value. Consumed by SerializableKeysMixin.

  • unserialize – a callback for custom unserialization of the field value. Consumed by SerializableKeysMixin.

  • exporter – a callback for custom export of the field value. Consumed by tmt.export.Exportable.

tmt.container.key_to_option(key: str) str

Convert a key name to corresponding option name

tmt.container.option_to_key(option: str) str

Convert an option name to corresponding key name