Bundles¶
There is a class for each bundle type:
ConfigBundle,
ProductBundle,
RecipeBundle,
ResultsBundle, and
TestResultBundle.
Each class adds bundle-specific data to the shared loading and export API. See Create and read your first bundle for a complete example.
Loading and initialization¶
The constructor creates an uninitialized bundle. Its create() method sets
its contents once. Factory methods return an initialized bundle:
Bundle.from_file_factory(path)reads XML, a ZIP archive, or a directory and detects the bundle class.ConfigBundle.from_file_factory(path)and the other concrete factories require the XML root to match the requested bundle type.from_bytes_factory(data)reads XML or ZIP bytes already in memory.
Directory and ZIP factories use the bundle’s default XML filename unless
xml_name is supplied. Recipe, configuration, and product defaults are
recipe.xml, config.xml, and product.xml. Results and self-test
reports both use result.xml. Type detection can identify other root XML
filenames, but loading still requires the appropriate xml_name.
Factory keyword arguments override fields in an optional
BundleFactoryArguments object.
XML schema validation and file signature validation are enabled by default.
validate_xml=False disables schema validation, not all parsing and
application-level checks. location_base changes diagnostic locations,
not the base directory for attachments.
Public-key authentication is opt-in through verification=VerificationOptions(...).
Use signing=SigningOptions(...) on exports to sign their final bytes.
See Bundle verification for trust policies, strict loading and atomic output rules.
Added in version 9.0.0: The verification and signing options.
Ownership and recreation¶
A bundle owns its elements. Child elements passed to create() must belong
to that bundle. After initialization, attributes cannot be assigned again.
An element’s recreate(target_bundle, **changes) method returns a new
element with selected fields replaced. Unspecified fields retain their values.
Most bundle classes reject direct recreate() calls. A modified bundle is
built by recreating its elements into a new bundle, then calling create().
TestResultBundle.recreate() is the report-specific exception.
snapshot_bundle() creates a complete
independent copy of a bundle.
Ordinary element recreation keeps attachment references to their original source. Those files and source bundles must remain available until export. Self-test fixtures and report records instead copy attachments into independent storage. See Self-test declarations and reports for those ownership rules.
Close loaded bundles with contextlib.closing() or close().
The to_buffer(), to_file(), and to_directory() export methods close
the exported bundle. Access after export is unsupported. to_buffer() leaves
the caller’s buffer open. to_file() closes a supplied file descriptor.
Output formats¶
to_file() and to_buffer() produce XML when the bundle has no external
attachments and zip=False. Otherwise, they produce a ZIP archive. The output
filename extension does not determine the format. to_directory() writes
XML and attachments to a directory.
On export, xml_name must be a valid root filename such as custom.xml.
Empty names, path separators including backslashes, absolute or drive paths, and
filenames invalid on Windows are rejected with
UnsafeBundleError. Directory export
also rejects existing XML symlinks that point outside the output directory.
Without public-key signing, the Python export methods write directly to the
destination. They validate the XML filename and prepare attachment export paths
before opening an output file or creating an output directory. Rejection during this preparation
preserves an existing destination and does not create a missing destination.
Once writing starts, to_file() overwrites an existing file and requires its
parent directory to exist. Later read or write failures can leave partial output. The
command-line tools in Command line interface instead write a temporary file before replacing
the destination.
Export keyword arguments override fields in an optional
FileConstructionArguments or
DirectoryConstructionArguments
object. These argument classes document all defaults.
Optional deduplication¶
Added in version 9.0.0.
Use deduplication when the same definition or attachment appears more than once in a bundle and you want smaller output. The first copy stays in full. Later copies become references to it, or share its stored bytes. Deduplication is off by default, and readers of deduplicated bundles need the reference support described below. The matching rules after the example are mainly for authors of tools that read or write bundles directly.
All export methods accept two keyword-only construction options, also available on
BundleConstructionArguments,
FileConstructionArguments, and
DirectoryConstructionArguments.
Both default to False and are independent of optimize.
|
|
Behavior |
|---|---|---|
|
|
Write each XML definition in full and store each external attachment separately. |
|
|
Replace identical XML definitions with references. |
|
|
Share identical external payloads, then deduplicate XML definitions. |
|
|
Raise |
Keyword arguments override values in the supplied args object before validation.
For example:
bundle.to_file('shared.zip', deduplicate=True, deduplicate_attachments=True)
How XML definitions are matched¶
XML deduplication compares schema-defined file, option, and checklet nodes.
It includes effective inherited attributes, wildcard attributes, ordered children,
and exact mixed-content whitespace. Attribute order does not affect equality.
Explicit identities remain intact. Anonymous duplicates use deterministic IDs and
ref-only nodes, with the first matching definition retained.
The schema requires document-wide unique XML IDs. Deduplicating export raises
ValueError for duplicate explicit XML IDs, including when the same identified
fixture is embedded twice. It does not rename explicit IDs.
Arbitrary XML inside node content is content and does not supply definitions.
Current readers resolve generated references automatically in every bundle type.
Embedded configurations, products, and results have separate reference scopes.
Each mock result and each report case’s diagnostic files also has its own scope.
Existing higher-level references retain their lookup order and inheritance behavior.
Additional scope-wide references use the target’s effective attributes without
combining destination prefixes. Forward references work. Missing targets, wrong
types, ambiguous IDs, cycles, and references outside the current scope raise
InvalidRefError.
Consumers of deduplicated artifacts need a reader with this scope-wide reference support.
The build command exposes both deduplication options.
How attachment payloads are matched¶
Attachment sharing applies to external files, repositories, and embedded test or report attachments. Inline content stays inline. Regular files share a payload only when their size, uncompressed bytes, and effective stored executable permissions match. SHA-256 groups candidates; streamed byte comparison confirms equality. Existing XML signatures and ZIP CRCs do not establish payload identity. Directories share as complete trees, including relative member paths, file contents, executable permissions, and empty directories. Members of distinct trees are not shared individually.
The lexicographically first allocated export path is the canonical payload location. All matching external references point there, and ZIP and directory exports write that file or tree once. Logical names, classes, types, executable attributes, and signatures remain independent of payload sharing. Payloads can be shared across embedded bundles in one artifact, while their XML reference scopes remain separate. Comparisons read file content in bounded chunks and propagate source-read failures. Each export recalculates which attachment paths can share content.
Timestamps do not affect payload identity. Shared ZIP entries use the canonical
source’s timestamps. Directory exports keep their existing timestamp behavior.
Payload comparison reads uncompressed bytes even when the final write copies the
canonical source’s compressed ZIP data. Eligible compressed copying remains enabled;
always_recompress=True forces recompression with the requested settings.
Base API¶
- class momotor.bundles.Bundle(base=None, zip_wrapper=None, *, _store=None)¶
Base class for reading and exporting Momotor bundles.
Concrete bundle constructors allocate an uninitialized object. Their
create()methods initialize its contents once. Factory methods return initialized bundles.- Parameters:
base (
str|Path|None) – Directory used to resolve relative filesystem attachment paths.zip_wrapper (
ZipWrapper|None) – ZIP source used internally by the factory methods.
- classmethod detect(path_or_data, *, args=None, **kwargs)¶
Detect type of bundle and return the corresponding class.
- Parameters:
path_or_data (
Path|bytes|memoryview) – APathto the bundle file or directory, or abytesormemoryviewcontaining a bundle XML or ZIP fileargs (
BundleFactoryArguments|None) – arguments for the detectionkwargs – alternative way to provide the arguments. Arguments in kwargs override arguments in args
- Return type:
- Returns:
The matching
Bundleclass, eitherRecipeBundle,ConfigBundle,ProductBundle,ResultsBundle, orTestResultBundle- Raises:
FileNotFoundErrorif the path does not exist- Raises:
InvalidBundleif path does not contain a bundle
- classmethod from_bytes_factory(data, *, args=None, **kwargs)¶
Read bundle from memory, either a
bytesormemoryviewobject. When called from theBundlebase class, usesdetect()to autodetect the type of bundle. When called from a specific bundle class specialization, raisesBundleFormatErrorif the XML root has the wrong bundle type.Make sure to call
close()either explicitly or usingcontextlib.closing()when done with the bundle to release all resources- Parameters:
data (
bytes|memoryview) – Bundle dataargs (
BundleFactoryArguments|None) – arguments for the factorykwargs – alternative way to provide the arguments. Arguments in kwargs override arguments in args
- Return type:
Self- Returns:
the bundle
- Raises:
InvalidBundleif data does not contain a valid bundle
- classmethod from_file_factory(path, *, args=None, **kwargs)¶
Read bundle from a local file or directory. When called from the
Bundlebase class, usesdetect()to autodetect the type of bundle. When called from a specific bundle class specialization, raisesBundleFormatErrorif the XML root has the wrong bundle type.Make sure to call
close()either explicitly or usingcontextlib.closing()when done with the bundle to release all resources- Parameters:
path (
str|PathLike[str]) – Either a file or directory. When it is a file, it can be an XML file or a zip file. When it is a directory, that directory should contain a <bundle>.xml fileargs (
BundleFactoryArguments|None) – arguments for the factorykwargs – alternative way to provide the arguments. Arguments in kwargs override arguments in args
- Return type:
Self- Returns:
the bundle
- Raises:
InvalidBundleif path does not contain a valid bundle
- classmethod recreate_list(elements, target_bundle, filter=None, **kwargs)¶
Recreate a list of elements using the
recreate()method- Parameters:
elements (
Iterable[Self] |None) – List of elements to recreate (can beNone)target_bundle (
Bundle) – The target bundlefilter (
Callable[[Self],bool] |None) – An optional callable to filter the list of elements before recreation. The callable receives an element and should return a boolean. Only elements for which the callable returnsTruewill be recreatedkwargs – Additional keyword arguments are passed on to
recreate()
- Return type:
- Returns:
a list of elements or
Noneif elements param wasNone
- abstractmethod static get_category()¶
Get the category for this bundle
- Return type:
- close()¶
Close bundle and release all files and resources held.
Any access to the bundle after calling
close()is undefined.
- abstractmethod create(*args, **kwargs)¶
Set this element’s attributes
Usage:
element = Element(bundle).create(...)
- Return type:
Self- Returns:
self
- to_buffer(buffer, *, args=None, **kwargs)¶
Export the bundle to a binary buffer and close the bundle.
The caller’s buffer remains open. Output is XML when the bundle has no attachments and
zip=False. Otherwise, output is a ZIP archive containing XML and attachments. Do not use the bundle after export, even if writing fails.- Parameters:
args (
FileConstructionArguments|None) – Export settings. Omission usesFileConstructionArgumentsdefaults.kwargs – Export settings that override fields in
args.
- Return type:
- Returns:
BundleFormat.XMLorBundleFormat.ZIP.- Raises:
UnsafeBundleError – If
xml_nameis not a safe root filename.
- to_directory(path, *, args=None, **kwargs)¶
Export XML and attachments to a directory and close the bundle.
The XML uses
xml_nameor the bundle’s default filename. Attachment paths are relative to that XML file. The XML file is overwritten. Existing attachments can be overwritten or merged with copied directories. Source attachment paths must not overlap the destination.- Parameters:
path (
Path) – Destination directory. Missing directories are created.args (
DirectoryConstructionArguments|None) – Export settings. Omission usesDirectoryConstructionArgumentsdefaults.kwargs – Export settings that override fields in
args.
- Raises:
UnsafeBundleError – If
xml_nameis unsafe or escapes via a symlink.- Return type:
- to_file(fd_or_path, *, args=None, **kwargs)¶
Export the bundle to a file and close the bundle.
Output is XML when there are no attachments and
zip=False. Otherwise, output is ZIP. The filename extension does not select the format. The destination is overwritten. Its parent directory must already exist.- Parameters:
fd_or_path (
int|str|Path) – Path or open file descriptor. The descriptor is closed after writing. If export preparation fails, the descriptor remains open and its contents are unchanged.args (
FileConstructionArguments|None) – Export settings. Omission usesFileConstructionArgumentsdefaults.kwargs – Export settings that override fields in
args.
- Return type:
- Returns:
BundleFormat.XMLorBundleFormat.ZIP.- Raises:
UnsafeBundleError – If
xml_nameis not a safe root filename.
ConfigBundle¶
A ConfigBundle contains all configuration needed by the recipe.
It provides a Python interface to read and create XML files of
ConfigComplexType
See the documentation of the base class Bundle on how to use bundles.
Associated recipes¶
Added in version 9.0.0.
The optional for-recipe attribute lists the recipes associated with a configuration.
Multiple values are separated by whitespace:
<config xmlns="http://momotor.org/1.0" for-recipe="recipe-a org.example:recipe-*"/>
The for_recipe property returns an immutable tuple.
The bundle reader splits values on whitespace without validating or interpreting them.
Special characters, including wildcards, are preserved, as are value order and duplicates.
Consuming tools decide whether the values express preferences or requirements, and how to match them to recipes.
An absent or empty attribute produces an empty tuple. Export omits the attribute when the tuple is empty.
Runtime projections preserve the values.
The attribute applies to standalone configuration bundles. Embedded self-test configurations omit it,
since their containing recipe or configuration already determines the recipe context.
The create() method accepts a whitespace-separated string
or an iterable of strings. Each string is split on whitespace:
from momotor.bundles import ConfigBundle
config = ConfigBundle().create(for_recipe="recipe-a org.example:recipe-*")
assert config.for_recipe == ('recipe-a', 'org.example:recipe-*')
- class momotor.bundles.ConfigBundle(base=None, zip_wrapper=None, *, _store=None)¶
A config bundle. This implements the interface to create and access Momotor configuration files
Concrete bundle constructors allocate an uninitialized object. Their
create()methods initialize its contents once. Factory methods return initialized bundles.- Parameters:
base (
str|Path|None) – Directory used to resolve relative filesystem attachment paths.zip_wrapper (
ZipWrapper|None) – ZIP source used internally by the factory methods.
- copy_files_to(destination, *, files=None)¶
Copy files attached using the files nodes to a directory
Copies are incremental. A failure retains earlier successful copies and does not remove pre-existing files or overwrite existing targets.
- create(*, id=None, meta=None, options=None, files=None, tests=None, for_recipe=None)¶
Set all attributes for this
ConfigBundleUsage:
config = ConfigBundle(...).create(id=..., meta=..., options=..., files=...)
- Parameters:
options (
Iterable[Option] |None) – list of options (optional)tests (
Iterable[TestCase] |None) – self-test cases using this configuration unchanged (optional)for_recipe (
str|Iterable[str] |None) – Whitespace-separated values or an iterable of values forfor-recipe. Values are split on whitespace without further validation. Omission produces an empty tuple.
- Return type:
Self- Returns:
self
- get_option_value(name, *, domain='checklet', default=<object object>)¶
Get the value for a single option. If multiple options match, the value of the first one found will be returned.
- Parameters:
- Return type:
- Returns:
The option value
- Raises:
- get_options(name, *, domain='checklet')¶
Get options
- Parameters:
- Return type:
- Returns:
A filterable tuple of all matching options.
- property files: FilterableTuple[File]¶
files children
- property for_recipe: tuple[str, ...]¶
The whitespace-separated
for-recipevalues, without interpretation or validation.Consuming tools decide whether these values express preferences or requirements, and whether special characters such as wildcards have meaning.
Added in version 9.0.0.
- property options: FilterableTuple[Option]¶
options children
- property tests: KeyedTuple[TestCase]¶
Immutable test cases accessible by index or author ID.
ProductBundle¶
A ProductBundle contains the product to be evaluated by the recipe.
It provides a Python interface to read and create XML files of
ProductComplexType
See the documentation of the base class Bundle on how to use bundles.
Associated recipes and configurations¶
Added in version 9.0.0.
The optional for-recipe and for-config attributes list the recipes and configurations
associated with a standalone product bundle:
<product xmlns="http://momotor.org/1.0"
for-recipe="recipe-a org.example:recipe-*"
for-config="config-a config-*"/>
The for_recipe and
for_config properties return independent immutable tuples.
Values are split on whitespace without validation or interpretation. Special characters, order,
and duplicates are preserved. Consuming tools decide whether the values express preferences or requirements,
and how to match them. An absent or empty attribute produces an empty tuple, and export omits empty attributes.
Runtime projections preserve both fields. Embedded self-test products omit them,
since their containing recipe or configuration determines the execution context.
The create() method accepts whitespace-separated strings
or iterables of strings for both fields. Each string is split on whitespace:
from momotor.bundles import ProductBundle
product = ProductBundle().create(for_recipe="recipe-a recipe-*", for_config=['config-a', 'config-*'])
assert product.for_recipe == ('recipe-a', 'recipe-*')
assert product.for_config == ('config-a', 'config-*')
- class momotor.bundles.ProductBundle(base=None, zip_wrapper=None, *, _store=None)¶
A product bundle. This implements the interface to create and access Momotor product files
Concrete bundle constructors allocate an uninitialized object. Their
create()methods initialize its contents once. Factory methods return initialized bundles.- Parameters:
base (
str|Path|None) – Directory used to resolve relative filesystem attachment paths.zip_wrapper (
ZipWrapper|None) – ZIP source used internally by the factory methods.
- copy_files_to(destination, *, files=None)¶
Copy files attached using the files nodes to a directory
Copies are incremental. A failure retains earlier successful copies and does not remove pre-existing files or overwrite existing targets.
- create(*, id=None, meta=None, options=None, files=None, properties=None, for_recipe=None, for_config=None)¶
Set all attributes for this
ProductBundleUsage:
product = ProductBundle(...).create(id=..., meta=..., options=..., files=..., properties=...)
- Parameters:
options (
Iterable[Option] |None) – list of options (optional)properties (
Iterable[Property] |None) – list of properties (optional)for_recipe (
str|Iterable[str] |None) – Whitespace-separated values or an iterable of values forfor-recipe. Values are split on whitespace without further validation. Omission produces an empty tuple.for_config (
str|Iterable[str] |None) – Whitespace-separated values or an iterable of values forfor-config. Values are split on whitespace without further validation. Omission produces an empty tuple.
- Return type:
Self- Returns:
self
- get_option_value(name, *, domain='checklet', default=<object object>)¶
Get the value for a single option. If multiple options match, the value of the first one found will be returned.
- Parameters:
- Return type:
- Returns:
The option value
- Raises:
- get_options(name, *, domain='checklet')¶
Get options
- Parameters:
- Return type:
- Returns:
A filterable tuple of all matching options.
- get_properties(name)¶
Get properties
- Parameters:
name (
str) – name of the properties to get- Return type:
- Returns:
A list of all matching properties.
- get_property_value(name, *, default=<object object>)¶
Get the value for a single property. If multiple properties match, the value of the first one found will be returned
- property files: FilterableTuple[File]¶
files children
- property for_config: tuple[str, ...]¶
The whitespace-separated
for-configvalues, without interpretation or validation.Consuming tools decide whether these values express preferences or requirements, and whether special characters such as wildcards have meaning.
Added in version 9.0.0.
- property for_recipe: tuple[str, ...]¶
The whitespace-separated
for-recipevalues, without interpretation or validation.Consuming tools decide whether these values express preferences or requirements, and whether special characters such as wildcards have meaning.
Added in version 9.0.0.
- property options: FilterableTuple[Option]¶
options children
- property properties: FilterableTuple[Property]¶
properties children
RecipeBundle¶
A RecipeBundle defines the steps that process a product into results.
It provides a Python interface to read and create XML files of
RecipeComplexType
See the documentation of the base class Bundle on how to use bundles.
- class momotor.bundles.RecipeBundle(base=None, zip_wrapper=None, *, _store=None)¶
A recipe bundle. This implements the interface to create and access Momotor recipe files
Concrete bundle constructors allocate an uninitialized object. Their
create()methods initialize its contents once. Factory methods return initialized bundles.- Parameters:
base (
str|Path|None) – Directory used to resolve relative filesystem attachment paths.zip_wrapper (
ZipWrapper|None) – ZIP source used internally by the factory methods.
- copy_files_to(destination, *, files=None)¶
Copy files attached using the files nodes to a directory
Copies are incremental. A failure retains earlier successful copies and does not remove pre-existing files or overwrite existing targets.
- create(*, id=None, meta=None, options=None, files=None, steps, tests=None)¶
Set all attributes for this
RecipeBundleUsage:
recipe = RecipeBundle(...).create(id=..., meta=..., options=..., files=..., steps=..., tests=...)
- get_option_value(name, *, domain='checklet', default=<object object>)¶
Get the value for a single option. If multiple options match, the value of the first one found will be returned.
- Parameters:
- Return type:
- Returns:
The option value
- Raises:
- get_options(name, *, domain='checklet')¶
Get options
- Parameters:
- Return type:
- Returns:
A filterable tuple of all matching options.
- property files: FilterableTuple[File]¶
files children
- property options: FilterableTuple[Option]¶
options children
- property steps: KeyedTuple[Step]¶
The recipe’s steps
- property tests: KeyedTuple[TestCase]¶
Immutable test cases accessible by index or author ID.
ResultsBundle¶
A ResultsBundle contains the results of the recipe applied to a product.
It provides a Python interface to read and create XML files of
ResultsComplexType
It shares its result collection API with Results
See the documentation of the base class Bundle on how to use bundles.
- class momotor.bundles.ResultsBundle(base=None, zip_wrapper=None, *, _store=None)¶
A results bundle. This implements the interface to create and access Momotor result files
Concrete bundle constructors allocate an uninitialized object. Their
create()methods initialize its contents once. Factory methods return initialized bundles.- Parameters:
base (
str|Path|None) – Directory used to resolve relative filesystem attachment paths.zip_wrapper (
ZipWrapper|None) – ZIP source used internally by the factory methods.
- create(*, id=None, meta=None, results=None)¶
Set all attributes for this
ResultsBundleUsage:
results = ResultsBundle(...).create(id=..., meta=..., results=...)
- property results: ResultKeyedTuple¶
results children
- momotor.bundles.results.create_error_result_bundle(result_id, status, report=None, **properties)¶
Helper to create an error result bundle with a single step with an error
- Parameters:
- Return type:
- Returns:
A
ResultsBundlewith the error step
TestResultBundle¶
Changed in version 9.0.0: Replaced the grouped results API with immutable case records.
Earlier releases already shipped this class name with a results
collection. Its documentation marked self-testing as not yet
implemented and subject to change. See Migration.
A TestResultBundle contains recipe and configuration case verdicts,
assertion diagnostics, and ordinary execution results.
It provides a Python interface to read and create XML files of
TestResultComplexType
See the documentation of the base class Bundle on how to use bundles.
See Self-test declarations and reports for the authoring and report contracts.
- class momotor.bundles.TestResultBundle(base=None, zip_wrapper=None, *, _store=None)¶
A report with immutable case records and totals derived from those records.
Changed in version 9.0.0: Replaced the grouped
resultsAPI of earlier releases with immutable case records.- create(*, cases, format_version=1, complete=True, run_id=None, source_hashes=None, selection=None, evaluator_version=None, meta=None)¶
Create a report and take independent ownership of its result attachments.
- Parameters:
cases (
Iterable[CaseReport]) – Every selected case, including unfinished or cancelled cases.format_version (
int) – Report format version, currently 1.complete (
bool) – Whether the run is terminal.source_hashes (
Mapping[str,str] |None) – Original recipe/configuration hashes.selection (
Iterable[str] |None) – Frozen selected identities; defaults to case order.evaluator_version (
str|None) – Evaluator implementation version.
- Returns:
This bundle.
- Raises:
ValueError – If identities, selection, format version, or completeness disagree.
- recreate(target_bundle, **kwargs)¶
Copy this report into a new bundle with independent attachment ownership.
- property cases: KeyedTuple[CaseReport]¶
Case records indexed by qualified runtime identity.