From 06439a96c321fca27aaa8057d533088d917ebf48 Mon Sep 17 00:00:00 2001 From: Wiebe Vandendriessche Date: Thu, 26 Nov 2026 15:03:20 +0100 Subject: [PATCH] feat: add support for Component `data` and `modelParameters.datasets` Signed-off-by: Wiebe Vandendriessche --- cyclonedx/model/component.py | 38 +- cyclonedx/model/data.py | 652 ++++++++++++++++++ cyclonedx/model/graphics.py | 186 +++++ cyclonedx/model/model_card.py | 301 ++++---- docs/responsibilities_capabilities.rst | 2 + tests/_data/models.py | 122 ++++ .../enum_ComponentDataKind-1.5.json.bin | 54 ++ .../enum_ComponentDataKind-1.5.xml.bin | 22 + .../enum_ComponentDataKind-1.6.json.bin | 54 ++ .../enum_ComponentDataKind-1.6.xml.bin | 38 + .../enum_ComponentDataKind-1.7.json.bin | 54 ++ .../enum_ComponentDataKind-1.7.xml.bin | 38 + ..._bom_v1_5_with_data_component-1.5.json.bin | 149 ++++ ...t_bom_v1_5_with_data_component-1.5.xml.bin | 109 +++ ..._bom_v1_5_with_data_component-1.6.json.bin | 161 +++++ ...t_bom_v1_5_with_data_component-1.6.xml.bin | 121 ++++ ..._bom_v1_5_with_data_component-1.7.json.bin | 161 +++++ ...t_bom_v1_5_with_data_component-1.7.xml.bin | 121 ++++ ...v1_5_with_model_card_datasets-1.5.json.bin | 74 ++ ..._v1_5_with_model_card_datasets-1.5.xml.bin | 47 ++ ...v1_5_with_model_card_datasets-1.6.json.bin | 74 ++ ..._v1_5_with_model_card_datasets-1.6.xml.bin | 47 ++ ...v1_5_with_model_card_datasets-1.7.json.bin | 74 ++ ..._v1_5_with_model_card_datasets-1.7.xml.bin | 47 ++ tests/test_enums.py | 32 + tests/test_model_component.py | 19 + tests/test_model_component_data.py | 451 ++++++++++++ tests/test_model_model_card.py | 41 +- 28 files changed, 3099 insertions(+), 190 deletions(-) create mode 100644 cyclonedx/model/data.py create mode 100644 cyclonedx/model/graphics.py create mode 100644 tests/_data/snapshots/enum_ComponentDataKind-1.5.json.bin create mode 100644 tests/_data/snapshots/enum_ComponentDataKind-1.5.xml.bin create mode 100644 tests/_data/snapshots/enum_ComponentDataKind-1.6.json.bin create mode 100644 tests/_data/snapshots/enum_ComponentDataKind-1.6.xml.bin create mode 100644 tests/_data/snapshots/enum_ComponentDataKind-1.7.json.bin create mode 100644 tests/_data/snapshots/enum_ComponentDataKind-1.7.xml.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_data_component-1.5.json.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_data_component-1.5.xml.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_data_component-1.6.json.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_data_component-1.6.xml.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_data_component-1.7.json.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_data_component-1.7.xml.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.5.json.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.5.xml.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.6.json.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.6.xml.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.7.json.bin create mode 100644 tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.7.xml.bin create mode 100644 tests/test_model_component_data.py diff --git a/cyclonedx/model/component.py b/cyclonedx/model/component.py index 7a5136c3..827c2662 100644 --- a/cyclonedx/model/component.py +++ b/cyclonedx/model/component.py @@ -66,6 +66,7 @@ from .component_evidence import ComponentEvidence, _ComponentEvidenceSerializationHelper from .contact import OrganizationalContact, OrganizationalEntity from .crypto import CryptoProperties +from .data import ComponentData from .dependency import Dependable from .issue import IssueType from .license import License, LicenseRepository, _LicenseRepositorySerializationHelper @@ -1003,6 +1004,7 @@ def __init__( properties: Optional[Iterable[Property]] = None, release_notes: Optional[ReleaseNotes] = None, model_card: Optional[ModelCard] = None, + data: Optional[Iterable[ComponentData]] = None, cpe: Optional[str] = None, swid: Optional[Swid] = None, pedigree: Optional[Pedigree] = None, @@ -1045,6 +1047,7 @@ def __init__( self.evidence = evidence self.release_notes = release_notes self.model_card = model_card + self.data = data or [] self.crypto_properties = crypto_properties self.tags = tags or [] # spec-deprecated properties below @@ -1645,16 +1648,28 @@ def model_card(self) -> Optional[ModelCard]: def model_card(self, model_card: Optional[ModelCard]) -> None: self._model_card = model_card - # @property - # ... - # @serializable.view(SchemaVersion1Dot5) - # @serializable.xml_sequence(23) - # def data(self) -> ...: - # ... # TODO since CDX1.5 - # - # @data.setter - # def data(self, ...) -> None: - # ... # TODO since CDX1.5 + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_array(serializable.XmlArraySerializationType.FLAT, 'data') + @serializable.xml_sequence(27) + def data(self) -> 'SortedSet[ComponentData]': + """ + This object SHOULD be specified for any component of type `data` and MUST NOT be specified for other + component types. + + .. note:: + The XML schema of CycloneDX 1.5 allows at most one `data` element per component. + + Returns: + Set of `ComponentData` + """ + return self._data + + @data.setter + def data(self, data: Iterable[ComponentData]) -> None: + self._data = SortedSet(data) @property @serializable.view(SchemaVersion1Dot6) @@ -1740,7 +1755,8 @@ def __comparable_tuple(self) -> _ComparableTuple: _ComparableTuple(self.external_references), _ComparableTuple(self.properties), _ComparableTuple(self.components), self.evidence, self.release_notes, self.modified, _ComparableTuple(self.authors), _ComparableTuple(self.omnibor_ids), self.manufacturer, - self.crypto_properties, _ComparableTuple(self.tags), self.model_card, self.is_external, + self.crypto_properties, _ComparableTuple(self.tags), self.model_card, _ComparableTuple(self.data), + self.is_external, )) def __eq__(self, other: object) -> bool: diff --git a/cyclonedx/model/data.py b/cyclonedx/model/data.py new file mode 100644 index 00000000..8cea25dd --- /dev/null +++ b/cyclonedx/model/data.py @@ -0,0 +1,652 @@ +# This file is part of CycloneDX Python Library +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) OWASP Foundation. All Rights Reserved. + +""" +This set of classes represents the component data types in the CycloneDX standard. + +.. note:: + Introduced in CycloneDX v1.5. + +.. note:: + See the CycloneDX Schema for component data:\n + - XML: https://cyclonedx.org/docs/1.7/xml/#type_componentDataType\n + - JSON: https://cyclonedx.org/docs/1.7/json/#components_items_data +""" + +from collections.abc import Iterable +from enum import Enum +from typing import Any, Optional, Union + +import py_serializable as serializable +from sortedcontainers import SortedSet + +from .._internal.bom_ref import bom_ref_from_str as _bom_ref_from_str +from .._internal.compare import ComparableTuple as _ComparableTuple +from ..exception.model import InvalidValueException, MutuallyExclusivePropertiesException +from ..schema.schema import SchemaVersion1Dot5, SchemaVersion1Dot6, SchemaVersion1Dot7 +from . import AttachedText, Property, XsUri +from .bom_ref import BomRef +from .contact import OrganizationalContact, OrganizationalEntity +from .graphics import GraphicsCollection + + +@serializable.serializable_enum +class ComponentDataKind(str, Enum): + """Enumeration for `componentDataTypeEnumeration`: the type of data.""" + SOURCE_CODE = 'source-code' + CONFIGURATION = 'configuration' + DATASET = 'dataset' + DEFINITION = 'definition' + OTHER = 'other' + + +@serializable.serializable_class(ignore_unknown_during_deserialization=True) +class DataContents: + """Contents or references to the contents of the data being described.""" + + def __init__( + self, *, + attachment: Optional[AttachedText] = None, + url: Optional[XsUri] = None, + properties: Optional[Iterable[Property]] = None, + ) -> None: + self.attachment = attachment + self.url = url + self.properties = properties or [] + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(1) + def attachment(self) -> Optional[AttachedText]: + """ + An optional way to include textual or encoded data. + + Returns: + `AttachedText` if set else `None` + """ + return self._attachment + + @attachment.setter + def attachment(self, attachment: Optional[AttachedText]) -> None: + self._attachment = attachment + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(2) + def url(self) -> Optional[XsUri]: + """ + The URL to where the data can be retrieved. + + Returns: + `XsUri` if set else `None` + """ + return self._url + + @url.setter + def url(self, url: Optional[XsUri]) -> None: + self._url = url + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'property') + @serializable.xml_sequence(3) + def properties(self) -> 'SortedSet[Property]': + """ + Provides the ability to document properties in a name-value store. + + Returns: + Set of `Property` + """ + return self._properties + + @properties.setter + def properties(self, properties: Iterable[Property]) -> None: + self._properties = SortedSet(properties) + + def __comparable_tuple(self) -> _ComparableTuple: + return _ComparableTuple((self.attachment, self.url, _ComparableTuple(self.properties))) + + def __eq__(self, other: object) -> bool: + if isinstance(other, DataContents): + return self.__comparable_tuple() == other.__comparable_tuple() + return False + + def __lt__(self, other: Any) -> bool: + if isinstance(other, DataContents): + return self.__comparable_tuple() < other.__comparable_tuple() + return NotImplemented + + def __le__(self, other: Any) -> bool: + if isinstance(other, DataContents): + return self.__comparable_tuple() <= other.__comparable_tuple() + return NotImplemented + + def __ge__(self, other: Any) -> bool: + if isinstance(other, DataContents): + return self.__comparable_tuple() >= other.__comparable_tuple() + return NotImplemented + + def __hash__(self) -> int: + return hash(self.__comparable_tuple()) + + def __repr__(self) -> str: + return f'' + + +@serializable.serializable_class(ignore_unknown_during_deserialization=True) +class DataGovernanceResponsibleParty: + """ + A party that is responsible for data: either an organization or an individual. + + Exactly one of `organization` and `contact` MUST be supplied, as required by the JSON schema. + """ + + def __init__( + self, *, + organization: Optional[OrganizationalEntity] = None, + contact: Optional[OrganizationalContact] = None, + ) -> None: + if organization is None and contact is None: + raise MutuallyExclusivePropertiesException('Either `organization` or `contact` MUST be supplied') + self.organization = organization + self.contact = contact + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(1) + def organization(self) -> Optional[OrganizationalEntity]: + """ + The organization that is responsible for the data. + + Returns: + `OrganizationalEntity` if set else `None` + """ + return self._organization + + @organization.setter + def organization(self, organization: Optional[OrganizationalEntity]) -> None: + if organization is not None and getattr(self, '_contact', None) is not None: + raise MutuallyExclusivePropertiesException('`organization` and `contact` are mutually exclusive') + self._organization = organization + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.json_name('contact') + @serializable.xml_name('individual') + @serializable.xml_sequence(2) + def contact(self) -> Optional[OrganizationalContact]: + """ + The individual that is responsible for the data. + + Returns: + `OrganizationalContact` if set else `None` + """ + return self._contact + + @contact.setter + def contact(self, contact: Optional[OrganizationalContact]) -> None: + if contact is not None and getattr(self, '_organization', None) is not None: + raise MutuallyExclusivePropertiesException('`organization` and `contact` are mutually exclusive') + self._contact = contact + + def __comparable_tuple(self) -> _ComparableTuple: + return _ComparableTuple((self.organization, self.contact)) + + def __eq__(self, other: object) -> bool: + if isinstance(other, DataGovernanceResponsibleParty): + return self.__comparable_tuple() == other.__comparable_tuple() + return False + + def __lt__(self, other: Any) -> bool: + if isinstance(other, DataGovernanceResponsibleParty): + return self.__comparable_tuple() < other.__comparable_tuple() + return NotImplemented + + def __le__(self, other: Any) -> bool: + if isinstance(other, DataGovernanceResponsibleParty): + return self.__comparable_tuple() <= other.__comparable_tuple() + return NotImplemented + + def __ge__(self, other: Any) -> bool: + if isinstance(other, DataGovernanceResponsibleParty): + return self.__comparable_tuple() >= other.__comparable_tuple() + return NotImplemented + + def __hash__(self) -> int: + return hash(self.__comparable_tuple()) + + def __repr__(self) -> str: + return ( + f'' + ) + + +@serializable.serializable_class(ignore_unknown_during_deserialization=True) +class DataGovernance: + """Governance of the data: its custodians, stewards and owners.""" + + def __init__( + self, *, + custodians: Optional[Iterable[DataGovernanceResponsibleParty]] = None, + stewards: Optional[Iterable[DataGovernanceResponsibleParty]] = None, + owners: Optional[Iterable[DataGovernanceResponsibleParty]] = None, + ) -> None: + self.custodians = custodians or [] + self.stewards = stewards or [] + self.owners = owners or [] + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'custodian') + @serializable.xml_sequence(1) + def custodians(self) -> 'SortedSet[DataGovernanceResponsibleParty]': + """ + Data custodians are responsible for the safe custody, transport, and storage of data. + + Returns: + Set of `DataGovernanceResponsibleParty` + """ + return self._custodians + + @custodians.setter + def custodians(self, custodians: Iterable[DataGovernanceResponsibleParty]) -> None: + self._custodians = SortedSet(custodians) + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'steward') + @serializable.xml_sequence(2) + def stewards(self) -> 'SortedSet[DataGovernanceResponsibleParty]': + """ + Data stewards are responsible for data content, context, and associated business rules. + + Returns: + Set of `DataGovernanceResponsibleParty` + """ + return self._stewards + + @stewards.setter + def stewards(self, stewards: Iterable[DataGovernanceResponsibleParty]) -> None: + self._stewards = SortedSet(stewards) + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'owner') + @serializable.xml_sequence(3) + def owners(self) -> 'SortedSet[DataGovernanceResponsibleParty]': + """ + Data owners are concerned with risk and appropriate access to data. + + Returns: + Set of `DataGovernanceResponsibleParty` + """ + return self._owners + + @owners.setter + def owners(self, owners: Iterable[DataGovernanceResponsibleParty]) -> None: + self._owners = SortedSet(owners) + + def __comparable_tuple(self) -> _ComparableTuple: + return _ComparableTuple(( + _ComparableTuple(self.custodians), + _ComparableTuple(self.stewards), + _ComparableTuple(self.owners), + )) + + def __eq__(self, other: object) -> bool: + if isinstance(other, DataGovernance): + return self.__comparable_tuple() == other.__comparable_tuple() + return False + + def __lt__(self, other: Any) -> bool: + if isinstance(other, DataGovernance): + return self.__comparable_tuple() < other.__comparable_tuple() + return NotImplemented + + def __le__(self, other: Any) -> bool: + if isinstance(other, DataGovernance): + return self.__comparable_tuple() <= other.__comparable_tuple() + return NotImplemented + + def __ge__(self, other: Any) -> bool: + if isinstance(other, DataGovernance): + return self.__comparable_tuple() >= other.__comparable_tuple() + return NotImplemented + + def __hash__(self) -> int: + return hash(self.__comparable_tuple()) + + def __repr__(self) -> str: + return ( + f'' + ) + + +@serializable.serializable_class(ignore_unknown_during_deserialization=True) +class ComponentData: + """ + Inline data of a component, as defined by `componentDataType`: a dataset, source code, configuration, etc. + """ + + def __init__( + self, *, + type: ComponentDataKind, + bom_ref: Optional[Union[str, BomRef]] = None, + name: Optional[str] = None, + contents: Optional[DataContents] = None, + classification: Optional[str] = None, + sensitive_data: Optional[Iterable[str]] = None, + graphics: Optional[GraphicsCollection] = None, + description: Optional[str] = None, + governance: Optional[DataGovernance] = None, + ) -> None: + self._bom_ref = _bom_ref_from_str(bom_ref) + self.type = type + self.name = name + self.contents = contents + self.classification = classification + self.sensitive_data = sensitive_data or [] + self.graphics = graphics + self.description = description + self.governance = governance + + @property + @serializable.json_name('bom-ref') + @serializable.type_mapping(BomRef) + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_attribute() + @serializable.xml_name('bom-ref') + def bom_ref(self) -> BomRef: + """ + An identifier which can be used to reference the data elsewhere in the BOM. Every `bom-ref` must be unique + within the BOM. + + Returns: + `BomRef` + """ + return self._bom_ref + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(1) + def type(self) -> ComponentDataKind: + """ + The general theme or subject matter of the data being specified. + + Returns: + `ComponentDataKind` + """ + return self._type + + @type.setter + def type(self, type: ComponentDataKind) -> None: + self._type = type + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(2) + def name(self) -> Optional[str]: + """ + The name of the dataset. + + Returns: + `str` if set else `None` + """ + return self._name + + @name.setter + def name(self, name: Optional[str]) -> None: + self._name = name + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(3) + def contents(self) -> Optional[DataContents]: + """ + The contents or references to the contents of the data being described. + + Returns: + `DataContents` if set else `None` + """ + return self._contents + + @contents.setter + def contents(self, contents: Optional[DataContents]) -> None: + self._contents = contents + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(4) + def classification(self) -> Optional[str]: + """ + Data classification tags data according to its type, sensitivity, and value if altered, stolen, or destroyed. + + Returns: + `str` if set else `None` + """ + return self._classification + + @classification.setter + def classification(self, classification: Optional[str]) -> None: + self._classification = classification + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.json_name('sensitiveData') + @serializable.xml_array(serializable.XmlArraySerializationType.FLAT, 'sensitiveData') + @serializable.xml_sequence(5) + def sensitive_data(self) -> 'SortedSet[str]': + """ + A description of any sensitive data in a dataset. + + Returns: + Set of `str` + """ + return self._sensitive_data + + @sensitive_data.setter + def sensitive_data(self, sensitive_data: Iterable[str]) -> None: + self._sensitive_data = SortedSet(sensitive_data) + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(6) + def graphics(self) -> Optional[GraphicsCollection]: + """ + A collection of graphics that represent various measurements. + + Returns: + `GraphicsCollection` if set else `None` + """ + return self._graphics + + @graphics.setter + def graphics(self, graphics: Optional[GraphicsCollection]) -> None: + self._graphics = graphics + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(7) + def description(self) -> Optional[str]: + """ + A description of the dataset. Can describe size of dataset, whether it's downloadable, etc. + + Returns: + `str` if set else `None` + """ + return self._description + + @description.setter + def description(self, description: Optional[str]) -> None: + self._description = description + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(8) + def governance(self) -> Optional[DataGovernance]: + """ + Data governance captures information regarding data ownership, stewardship, and custodianship. + + Returns: + `DataGovernance` if set else `None` + """ + return self._governance + + @governance.setter + def governance(self, governance: Optional[DataGovernance]) -> None: + self._governance = governance + + def __comparable_tuple(self) -> _ComparableTuple: + return _ComparableTuple(( + self.type, self.bom_ref.value, self.name, self.contents, self.classification, + _ComparableTuple(self.sensitive_data), self.graphics, self.description, self.governance, + )) + + def __eq__(self, other: object) -> bool: + if isinstance(other, ComponentData): + return self.__comparable_tuple() == other.__comparable_tuple() + return False + + def __lt__(self, other: Any) -> bool: + if isinstance(other, ComponentData): + return self.__comparable_tuple() < other.__comparable_tuple() + if isinstance(other, DatasetReference): + return True # self before any DatasetReference + return NotImplemented + + def __le__(self, other: Any) -> bool: + if isinstance(other, ComponentData): + return self.__comparable_tuple() <= other.__comparable_tuple() + if isinstance(other, DatasetReference): + return True + return NotImplemented + + def __ge__(self, other: Any) -> bool: + if isinstance(other, ComponentData): + return self.__comparable_tuple() >= other.__comparable_tuple() + if isinstance(other, DatasetReference): + return False + return NotImplemented + + def __hash__(self) -> int: + return hash(self.__comparable_tuple()) + + def __repr__(self) -> str: + return f'' + + +class DatasetReference: + """ + A reference to a data component, as used by `modelCard.modelParameters.datasets`. + + The reference is either the `bom-ref` of a data component in the same BOM, + or a BOM-Link (`urn:cdx:...`) to an element of another BOM. + + .. note:: + Serialization is handled by :attr:`cyclonedx.model.model_card.ModelParameters.datasets`. + """ + + def __init__(self, *, ref: Union[str, BomRef, XsUri]) -> None: + self.ref = ref + + @property + def ref(self) -> Union[str, BomRef, XsUri]: + """ + The `bom-ref` of a data component, or a BOM-Link to one. + + Returns: + `str`, `BomRef` or `XsUri` + """ + return self._ref + + @ref.setter + def ref(self, ref: Union[str, BomRef, XsUri]) -> None: + # a `BomRef` may legitimately have no value yet, as it can be assigned when the BOM is serialized + if isinstance(ref, (str, XsUri)) and not str(ref): + raise InvalidValueException('`ref` MUST NOT be empty') + self._ref = ref + + def __comparable_tuple(self) -> _ComparableTuple: + return _ComparableTuple((str(self.ref),)) + + def __eq__(self, other: object) -> bool: + if isinstance(other, DatasetReference): + return self.__comparable_tuple() == other.__comparable_tuple() + return False + + def __lt__(self, other: Any) -> bool: + if isinstance(other, DatasetReference): + return self.__comparable_tuple() < other.__comparable_tuple() + if isinstance(other, ComponentData): + return False # self after any ComponentData + return NotImplemented + + def __le__(self, other: Any) -> bool: + if isinstance(other, DatasetReference): + return self.__comparable_tuple() <= other.__comparable_tuple() + if isinstance(other, ComponentData): + return False + return NotImplemented + + def __ge__(self, other: Any) -> bool: + if isinstance(other, DatasetReference): + return self.__comparable_tuple() >= other.__comparable_tuple() + if isinstance(other, ComponentData): + return True + return NotImplemented + + def __hash__(self) -> int: + return hash(self.__comparable_tuple()) + + def __repr__(self) -> str: + return f'' diff --git a/cyclonedx/model/graphics.py b/cyclonedx/model/graphics.py new file mode 100644 index 00000000..26a62cbe --- /dev/null +++ b/cyclonedx/model/graphics.py @@ -0,0 +1,186 @@ +# This file is part of CycloneDX Python Library +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) OWASP Foundation. All Rights Reserved. + +""" +Graphics types of the CycloneDX standard, shared by model cards and component data. + +.. note:: + See the CycloneDX Schema for graphics:\n + - XML: https://cyclonedx.org/docs/1.7/xml/#type_graphicsCollection\n + - JSON: https://cyclonedx.org/docs/1.7/json/#components_items_modelCard_quantitativeAnalysis_graphics +""" + +from collections.abc import Iterable +from typing import Any, Optional + +import py_serializable as serializable +from sortedcontainers import SortedSet + +from .._internal.compare import ComparableTuple as _ComparableTuple +from ..schema.schema import SchemaVersion1Dot5, SchemaVersion1Dot6, SchemaVersion1Dot7 +from . import AttachedText + + +@serializable.serializable_class(ignore_unknown_during_deserialization=True) +class Graphic: + """Graphic entry with optional name and image (AttachedText).""" + + def __init__(self, *, name: Optional[str] = None, image: Optional[AttachedText] = None) -> None: + self.name = name + self.image = image + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(1) + def name(self) -> Optional[str]: + """ + The name of the graphic. + + Returns: + `str` if set else `None` + """ + return self._name + + @name.setter + def name(self, name: Optional[str]) -> None: + self._name = name + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(2) + def image(self) -> Optional[AttachedText]: + """ + The graphic (vector or raster). Base64 encoding must be specified for binary images. + + Returns: + `AttachedText` if set else `None` + """ + return self._image + + @image.setter + def image(self, image: Optional[AttachedText]) -> None: + self._image = image + + def __comparable_tuple(self) -> _ComparableTuple: + return _ComparableTuple((self.name, self.image)) + + def __eq__(self, other: object) -> bool: + if isinstance(other, Graphic): + return self.__comparable_tuple() == other.__comparable_tuple() + return False + + def __lt__(self, other: Any) -> bool: + if isinstance(other, Graphic): + return self.__comparable_tuple() < other.__comparable_tuple() + return NotImplemented + + def __le__(self, other: Any) -> bool: + if isinstance(other, Graphic): + return self.__comparable_tuple() <= other.__comparable_tuple() + return NotImplemented + + def __ge__(self, other: Any) -> bool: + if isinstance(other, Graphic): + return self.__comparable_tuple() >= other.__comparable_tuple() + return NotImplemented + + def __hash__(self) -> int: + return hash(self.__comparable_tuple()) + + def __repr__(self) -> str: + return f'' + + +@serializable.serializable_class(ignore_unknown_during_deserialization=True) +class GraphicsCollection: + """A collection of graphics with optional description.""" + + def __init__(self, *, description: Optional[str] = None, collection: Optional[Iterable[Graphic]] = None) -> None: + self.description = description + self.collection = collection or [] + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(1) + def description(self) -> Optional[str]: + """ + A description of this collection of graphics. + + Returns: + `str` if set else `None` + """ + return self._description + + @description.setter + def description(self, description: Optional[str]) -> None: + self._description = description + + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(2) + @serializable.json_name('collection') + @serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'graphic') + @serializable.xml_name('collection') + def collection(self) -> 'SortedSet[Graphic]': + """ + A collection of graphics. + + Returns: + Set of `Graphic` + """ + return self._collection + + @collection.setter + def collection(self, collection: Iterable[Graphic]) -> None: + self._collection = SortedSet(collection) + + def __comparable_tuple(self) -> _ComparableTuple: + return _ComparableTuple((self.description, _ComparableTuple(self.collection))) + + def __eq__(self, other: object) -> bool: + if isinstance(other, GraphicsCollection): + return self.__comparable_tuple() == other.__comparable_tuple() + return False + + def __lt__(self, other: Any) -> bool: + if isinstance(other, GraphicsCollection): + return self.__comparable_tuple() < other.__comparable_tuple() + return NotImplemented + + def __le__(self, other: Any) -> bool: + if isinstance(other, GraphicsCollection): + return self.__comparable_tuple() <= other.__comparable_tuple() + return NotImplemented + + def __ge__(self, other: Any) -> bool: + if isinstance(other, GraphicsCollection): + return self.__comparable_tuple() >= other.__comparable_tuple() + return NotImplemented + + def __hash__(self) -> int: + return hash(self.__comparable_tuple()) + + def __repr__(self) -> str: + return f'' diff --git a/cyclonedx/model/model_card.py b/cyclonedx/model/model_card.py index d287cf04..8be0c43e 100644 --- a/cyclonedx/model/model_card.py +++ b/cyclonedx/model/model_card.py @@ -29,17 +29,22 @@ from collections.abc import Iterable from enum import Enum -from typing import Any, List, Optional, Union +from json import loads as json_loads +from typing import TYPE_CHECKING, Any, List, Optional, Union +from xml.etree.ElementTree import Element # nosec B405 import py_serializable as serializable from sortedcontainers import SortedSet from .._internal.bom_ref import bom_ref_from_str as _bom_ref_from_str from .._internal.compare import ComparableTuple as _ComparableTuple +from ..exception.serialization import CycloneDxDeserializationException from ..schema.schema import SchemaVersion1Dot5, SchemaVersion1Dot6, SchemaVersion1Dot7 -from . import AttachedText, ExternalReference, Property +from . import ExternalReference, Property, XsUri from .bom_ref import BomRef from .contact import OrganizationalEntity +from .data import ComponentData, DatasetReference +from .graphics import Graphic, GraphicsCollection # noqa: F401 # Graphic kept importable from here, since 11.13.0 @serializable.serializable_enum @@ -178,17 +183,105 @@ def __repr__(self) -> str: return f'' +Dataset = Union[ComponentData, DatasetReference] +"""TypeAlias for a union of the supported dataset entries of `modelParameters.datasets`. + +- :class:`~cyclonedx.model.data.ComponentData`: inline data +- :class:`~cyclonedx.model.data.DatasetReference`: reference to a data component +""" + +if TYPE_CHECKING: # pragma: no cover + # workaround for https://github.com/python/mypy/issues/5264 + # this code path is taken when static code analysis or documentation tools runs through. + class DatasetRepository(SortedSet[Dataset]): + """Collection of :class:`Dataset`. + + This is a `set`, not a `list`. Order MUST NOT matter here. + """ + +else: + class DatasetRepository(SortedSet): + """Collection of :class:`Dataset`. + + This is a `set`, not a `list`. Order MUST NOT matter here. + """ + + +class _DatasetRepositorySerializationHelper(serializable.helpers.BaseHelper): + """ THIS CLASS IS NON-PUBLIC API """ + + @staticmethod + def __ref_to_str(ref: Union[str, BomRef, XsUri]) -> str: + return str(ref) + + @staticmethod + def __str_to_ref(value: str) -> Union[BomRef, XsUri]: + # BOM-Link is the only reference form that is not a plain `bom-ref` + return XsUri(value) if value.startswith('urn:cdx:') else BomRef(value) + + @classmethod + def json_normalize(cls, o: DatasetRepository, *, + view: Optional[type[serializable.ViewType]], + **__: Any) -> Any: + if len(o) == 0: + return None + return [ + json_loads(d.as_json(view_=view)) # type:ignore[attr-defined] + if isinstance(d, ComponentData) + else {'ref': cls.__ref_to_str(d.ref)} + for d in o + ] + + @classmethod + def json_denormalize(cls, o: list[dict[str, Any]], + **__: Any) -> DatasetRepository: + repo = DatasetRepository() + for d in o: + if 'ref' in d: + repo.add(DatasetReference(ref=cls.__str_to_ref(str(d['ref'])))) + else: + repo.add(ComponentData.from_json(d)) # type:ignore[attr-defined] + return repo + + @classmethod + def xml_normalize(cls, o: DatasetRepository, *, + element_name: str, + view: Optional[type[serializable.ViewType]], + xmlns: Optional[str], + **__: Any) -> Optional[Element]: + if len(o) == 0: + return None + elem = Element(element_name) + for d in o: + if isinstance(d, ComponentData): + elem.append(d.as_xml( # type:ignore[attr-defined] + view_=view, as_string=False, element_name='dataset', xmlns=xmlns)) + else: + ref = Element(f'{{{xmlns}}}ref' if xmlns else 'ref') + ref.text = cls.__ref_to_str(d.ref) + elem.append(ref) + return elem + + @classmethod + def xml_denormalize(cls, o: Element, + default_ns: Optional[str], + **__: Any) -> DatasetRepository: + repo = DatasetRepository() + for d in o: + tag = d.tag if default_ns is None else d.tag.replace(f'{{{default_ns}}}', '') + if tag == 'ref': + repo.add(DatasetReference(ref=cls.__str_to_ref(d.text or ''))) + elif tag == 'dataset': + repo.add(ComponentData.from_xml(d, default_ns)) # type:ignore[attr-defined] + else: + raise CycloneDxDeserializationException(f'unexpected content: {d!r}') + return repo + + @serializable.serializable_class(ignore_unknown_during_deserialization=True) class ModelParameters: """`modelParameters` block within `modelCard`. - .. note:: - `datasets` is not supported yet (see issue #913): - - - passing non-empty `datasets` to the constructor raises `NotImplementedError`. - - `datasets` found while deserializing JSON/XML are ignored, - so re-serializing such a BOM drops them. - .. note:: `inputs` and `outputs` keep their given order and duplicates, because the position of an input/output is meaningful for a model signature. @@ -200,7 +293,7 @@ def __init__( task: Optional[str] = None, architecture_family: Optional[str] = None, model_architecture: Optional[str] = None, - datasets: Optional[Iterable[Any]] = None, # Unsupported placeholder until #913 lands. + datasets: Optional[Iterable[Dataset]] = None, inputs: Optional[Iterable[InputOutputMLParameters]] = None, outputs: Optional[Iterable[InputOutputMLParameters]] = None, ) -> None: @@ -208,16 +301,7 @@ def __init__( self.task = task self.architecture_family = architecture_family self.model_architecture = model_architecture - # datasets: The CycloneDX spec allows inline componentData or ref entries. - # This library has not yet implemented component.data (#913). To avoid emitting - # invalid or partial structures, any attempt to populate datasets is rejected. - if datasets is not None: - sentinel = object() - if next(iter(datasets), sentinel) is not sentinel: - raise NotImplementedError( - 'modelParameters.datasets is not yet supported. Tracked by issue #913.' - ) - self._datasets: 'SortedSet[Any]' = SortedSet() # always empty until implemented + self.datasets = datasets or [] self.inputs = inputs or [] self.outputs = outputs or [] @@ -303,8 +387,26 @@ def model_architecture(self) -> Optional[str]: def model_architecture(self, model_architecture: Optional[str]) -> None: self._model_architecture = model_architecture - # datasets intentionally omitted from serialization until #913 implemented. - # A future implementation will add a concrete union type and proper annotations. + @property + @serializable.view(SchemaVersion1Dot5) + @serializable.view(SchemaVersion1Dot6) + @serializable.view(SchemaVersion1Dot7) + @serializable.xml_sequence(5) + @serializable.json_name('datasets') + @serializable.type_mapping(_DatasetRepositorySerializationHelper) + @serializable.xml_name('datasets') + def datasets(self) -> 'SortedSet[Dataset]': + """ + The datasets used to train and evaluate the model: inline data or references to data components. + + Returns: + Set of `ComponentData` and `DatasetReference` + """ + return self._datasets + + @datasets.setter + def datasets(self, datasets: Iterable[Dataset]) -> None: + self._datasets = DatasetRepository(datasets) @property @serializable.view(SchemaVersion1Dot5) @@ -354,7 +456,7 @@ def __comparable_tuple(self) -> _ComparableTuple: self.task, self.architecture_family, self.model_architecture, - _ComparableTuple(self._datasets), + _ComparableTuple(self.datasets), _ComparableTuple(self.inputs), _ComparableTuple(self.outputs), )) @@ -591,159 +693,6 @@ def __repr__(self) -> str: return f'' -@serializable.serializable_class(ignore_unknown_during_deserialization=True) -class Graphic: - """Graphic entry with optional name and image (AttachedText).""" - - def __init__(self, *, name: Optional[str] = None, image: Optional[AttachedText] = None) -> None: - self.name = name - self.image = image - - @property - @serializable.view(SchemaVersion1Dot5) - @serializable.view(SchemaVersion1Dot6) - @serializable.view(SchemaVersion1Dot7) - @serializable.xml_sequence(1) - @serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING) - def name(self) -> Optional[str]: - """ - The name of the graphic. - - Returns: - `str` if set else `None` - """ - return self._name - - @name.setter - def name(self, name: Optional[str]) -> None: - self._name = name - - @property - @serializable.view(SchemaVersion1Dot5) - @serializable.view(SchemaVersion1Dot6) - @serializable.view(SchemaVersion1Dot7) - @serializable.xml_sequence(2) - def image(self) -> Optional[AttachedText]: - """ - The graphic (vector or raster). Base64 encoding must be specified for binary images. - - Returns: - `AttachedText` if set else `None` - """ - return self._image - - @image.setter - def image(self, image: Optional[AttachedText]) -> None: - self._image = image - - def __comparable_tuple(self) -> _ComparableTuple: - return _ComparableTuple((self.name, self.image)) - - def __eq__(self, other: object) -> bool: - if isinstance(other, Graphic): - return self.__comparable_tuple() == other.__comparable_tuple() - return False - - def __lt__(self, other: Any) -> bool: - if isinstance(other, Graphic): - return self.__comparable_tuple() < other.__comparable_tuple() - return NotImplemented - - def __le__(self, other: Any) -> bool: - if isinstance(other, Graphic): - return self.__comparable_tuple() <= other.__comparable_tuple() - return NotImplemented - - def __ge__(self, other: Any) -> bool: - if isinstance(other, Graphic): - return self.__comparable_tuple() >= other.__comparable_tuple() - return NotImplemented - - def __hash__(self) -> int: - return hash(self.__comparable_tuple()) - - def __repr__(self) -> str: - return f'' - - -@serializable.serializable_class(ignore_unknown_during_deserialization=True) -class GraphicsCollection: - """A collection of graphics with optional description.""" - - def __init__(self, *, description: Optional[str] = None, collection: Optional[Iterable[Graphic]] = None) -> None: - self.description = description - self.collection = collection or [] - - @property - @serializable.view(SchemaVersion1Dot5) - @serializable.view(SchemaVersion1Dot6) - @serializable.view(SchemaVersion1Dot7) - @serializable.xml_sequence(1) - @serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING) - def description(self) -> Optional[str]: - """ - A description of this collection of graphics. - - Returns: - `str` if set else `None` - """ - return self._description - - @description.setter - def description(self, description: Optional[str]) -> None: - self._description = description - - @property - @serializable.view(SchemaVersion1Dot5) - @serializable.view(SchemaVersion1Dot6) - @serializable.view(SchemaVersion1Dot7) - @serializable.xml_sequence(2) - @serializable.json_name('collection') - @serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'graphic') - @serializable.xml_name('collection') - def collection(self) -> 'SortedSet[Graphic]': - """ - A collection of graphics. - - Returns: - Set of `Graphic` - """ - return self._collection - - @collection.setter - def collection(self, collection: Iterable[Graphic]) -> None: - self._collection = SortedSet(collection) - - def __comparable_tuple(self) -> _ComparableTuple: - return _ComparableTuple((self.description, _ComparableTuple(self.collection))) - - def __eq__(self, other: object) -> bool: - if isinstance(other, GraphicsCollection): - return self.__comparable_tuple() == other.__comparable_tuple() - return False - - def __lt__(self, other: Any) -> bool: - if isinstance(other, GraphicsCollection): - return self.__comparable_tuple() < other.__comparable_tuple() - return NotImplemented - - def __le__(self, other: Any) -> bool: - if isinstance(other, GraphicsCollection): - return self.__comparable_tuple() <= other.__comparable_tuple() - return NotImplemented - - def __ge__(self, other: Any) -> bool: - if isinstance(other, GraphicsCollection): - return self.__comparable_tuple() >= other.__comparable_tuple() - return NotImplemented - - def __hash__(self) -> int: - return hash(self.__comparable_tuple()) - - def __repr__(self) -> str: - return f'' - - @serializable.serializable_class(ignore_unknown_during_deserialization=True) class QuantitativeAnalysis: """`quantitativeAnalysis` block within `modelCard`.""" diff --git a/docs/responsibilities_capabilities.rst b/docs/responsibilities_capabilities.rst index 6a773585..cc1dca25 100644 --- a/docs/responsibilities_capabilities.rst +++ b/docs/responsibilities_capabilities.rst @@ -36,8 +36,10 @@ Capabilities * :mod:`Component, Evidence, Patch, Pedigree, and more ` * :mod:`Organizational Contact and Entity ` * :mod:`Cryptographic properties and more ` + * :mod:`Component Data and Dataset Reference ` * :mod:`Definition and Standard ` * :mod:`Dependency ` + * :mod:`Graphics ` * :mod:`Impact and related Analysis ` * :mod:`Issue ` * :mod:`License Named, SPDX, Expression, and more ` diff --git a/tests/_data/models.py b/tests/_data/models.py index ebae62ca..fd1cdffb 100644 --- a/tests/_data/models.py +++ b/tests/_data/models.py @@ -88,6 +88,14 @@ RelatedCryptoMaterialState, RelatedCryptoMaterialType, ) +from cyclonedx.model.data import ( + ComponentData, + ComponentDataKind, + DataContents, + DataGovernance, + DataGovernanceResponsibleParty, + DatasetReference, +) from cyclonedx.model.definition import CreId, Definitions, Level, Requirement, Standard from cyclonedx.model.dependency import Dependency from cyclonedx.model.impact_analysis import ( @@ -546,6 +554,120 @@ def get_bom_v1_5_with_full_model_card() -> Bom: return bom +def get_bom_v1_5_with_data_component() -> Bom: + """Single component with a fully populated componentData entry (schema 1.5+ only).""" + + image_content = base64.b64encode(b'full-data-component-image').decode('utf-8') + + governance = DataGovernance( + custodians=[ + DataGovernanceResponsibleParty(organization=get_org_entity_1()), + DataGovernanceResponsibleParty(contact=get_org_contact_1()), + ], + stewards=[ + DataGovernanceResponsibleParty(organization=get_org_entity_1()), + ], + owners=[ + DataGovernanceResponsibleParty(contact=get_org_contact_1()), + DataGovernanceResponsibleParty(contact=get_org_contact_2()), + ], + ) + + data_component = ComponentData( + bom_ref='data-comp-full', + type=ComponentDataKind.DATASET, + name='training-dataset-v1', + contents=DataContents( + attachment=AttachedText( + content='aGVsbG8gd29ybGQ=', + content_type='text/plain', + encoding=Encoding.BASE_64, + ), + url=XsUri('https://example.com/datasets/training-v1.csv'), + properties=[Property(name='format', value='csv')], + ), + classification='public', + sensitive_data=['PII', 'financial'], + graphics=GraphicsCollection( + description='Data distribution plots,\nmulti-line', + collection=[ + Graphic( + name='class-distribution', + image=AttachedText( + content=image_content, + content_type='image/png', + encoding=Encoding.BASE_64, + ), + ), + Graphic( + name='feature\ncorrelation', + image=AttachedText( + content=image_content, + content_type='image/png', + encoding=Encoding.BASE_64, + ), + ), + ], + ), + description='Training dataset for the primary classifier, version 1.', + governance=governance, + ) + + component = Component( + name='full-data-component', + version='1.0.0', + type=ComponentType.DATA, + bom_ref='data-full', + purl=PackageURL(type='pypi', name='full-data-component', version='1.0.0'), + data=[data_component], + ) + + bom = _make_bom(components=[component]) + bom.register_dependency(component) + return bom + + +def get_bom_v1_5_with_model_card_datasets() -> Bom: + """Model card whose `modelParameters.datasets` hold inline data, a reference to a data component and a BOM-Link.""" + + data_component = Component( + name='referenced-dataset', + version='1.0.0', + type=ComponentType.DATA, + bom_ref='data-referenced', + data=[ComponentData(type=ComponentDataKind.DATASET, name='referenced-dataset')], + ) + + ml_component = Component( + name='model-with-datasets', + version='1.0.0', + type=ComponentType.MACHINE_LEARNING_MODEL, + bom_ref='ml-datasets', + model_card=ModelCard( + bom_ref='mc-datasets', + model_parameters=ModelParameters( + task='text-classification', + datasets=[ + ComponentData( + bom_ref='dataset-inline', + type=ComponentDataKind.DATASET, + name='inline-dataset', + description='Dataset described in place.', + contents=DataContents(url=XsUri('https://example.com/datasets/inline.csv')), + ), + DatasetReference(ref=data_component.bom_ref), + DatasetReference(ref=XsUri('urn:cdx:3e671687-395b-41f5-a30f-a58921a69b79/1#data-external')), + ], + ), + ), + ) + + bom = _make_bom(components=[data_component, ml_component]) + bom.register_dependency(data_component) + bom.register_dependency(ml_component, [data_component]) + return bom + + def get_bom_with_dependencies_valid() -> Bom: c1 = get_component_setuptools_simple() c2 = get_component_toml_with_hashes_with_references() diff --git a/tests/_data/snapshots/enum_ComponentDataKind-1.5.json.bin b/tests/_data/snapshots/enum_ComponentDataKind-1.5.json.bin new file mode 100644 index 00000000..9e3ff568 --- /dev/null +++ b/tests/_data/snapshots/enum_ComponentDataKind-1.5.json.bin @@ -0,0 +1,54 @@ +{ + "components": [ + { + "bom-ref": "dummy", + "data": [ + { + "name": "ComponentDataKind: CONFIGURATION", + "type": "configuration" + }, + { + "name": "ComponentDataKind: DATASET", + "type": "dataset" + }, + { + "name": "ComponentDataKind: DEFINITION", + "type": "definition" + }, + { + "name": "ComponentDataKind: OTHER", + "type": "other" + }, + { + "name": "ComponentDataKind: SOURCE_CODE", + "type": "source-code" + } + ], + "name": "dummy", + "type": "library" + } + ], + "dependencies": [ + { + "ref": "dummy" + } + ], + "metadata": { + "timestamp": "2023-01-07T13:44:32.312678+00:00" + }, + "properties": [ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + } + ], + "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac", + "version": 1, + "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.5" +} \ No newline at end of file diff --git a/tests/_data/snapshots/enum_ComponentDataKind-1.5.xml.bin b/tests/_data/snapshots/enum_ComponentDataKind-1.5.xml.bin new file mode 100644 index 00000000..40a39a6d --- /dev/null +++ b/tests/_data/snapshots/enum_ComponentDataKind-1.5.xml.bin @@ -0,0 +1,22 @@ + + + + 2023-01-07T13:44:32.312678+00:00 + + + + dummy + + source-code + ComponentDataKind: SOURCE_CODE + + + + + + + + val1 + val2 + + diff --git a/tests/_data/snapshots/enum_ComponentDataKind-1.6.json.bin b/tests/_data/snapshots/enum_ComponentDataKind-1.6.json.bin new file mode 100644 index 00000000..e4e552c8 --- /dev/null +++ b/tests/_data/snapshots/enum_ComponentDataKind-1.6.json.bin @@ -0,0 +1,54 @@ +{ + "components": [ + { + "bom-ref": "dummy", + "data": [ + { + "name": "ComponentDataKind: CONFIGURATION", + "type": "configuration" + }, + { + "name": "ComponentDataKind: DATASET", + "type": "dataset" + }, + { + "name": "ComponentDataKind: DEFINITION", + "type": "definition" + }, + { + "name": "ComponentDataKind: OTHER", + "type": "other" + }, + { + "name": "ComponentDataKind: SOURCE_CODE", + "type": "source-code" + } + ], + "name": "dummy", + "type": "library" + } + ], + "dependencies": [ + { + "ref": "dummy" + } + ], + "metadata": { + "timestamp": "2023-01-07T13:44:32.312678+00:00" + }, + "properties": [ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + } + ], + "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac", + "version": 1, + "$schema": "http://cyclonedx.org/schema/bom-1.6.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.6" +} \ No newline at end of file diff --git a/tests/_data/snapshots/enum_ComponentDataKind-1.6.xml.bin b/tests/_data/snapshots/enum_ComponentDataKind-1.6.xml.bin new file mode 100644 index 00000000..fe2c58af --- /dev/null +++ b/tests/_data/snapshots/enum_ComponentDataKind-1.6.xml.bin @@ -0,0 +1,38 @@ + + + + 2023-01-07T13:44:32.312678+00:00 + + + + dummy + + configuration + ComponentDataKind: CONFIGURATION + + + dataset + ComponentDataKind: DATASET + + + definition + ComponentDataKind: DEFINITION + + + other + ComponentDataKind: OTHER + + + source-code + ComponentDataKind: SOURCE_CODE + + + + + + + + val1 + val2 + + diff --git a/tests/_data/snapshots/enum_ComponentDataKind-1.7.json.bin b/tests/_data/snapshots/enum_ComponentDataKind-1.7.json.bin new file mode 100644 index 00000000..94c2069b --- /dev/null +++ b/tests/_data/snapshots/enum_ComponentDataKind-1.7.json.bin @@ -0,0 +1,54 @@ +{ + "components": [ + { + "bom-ref": "dummy", + "data": [ + { + "name": "ComponentDataKind: CONFIGURATION", + "type": "configuration" + }, + { + "name": "ComponentDataKind: DATASET", + "type": "dataset" + }, + { + "name": "ComponentDataKind: DEFINITION", + "type": "definition" + }, + { + "name": "ComponentDataKind: OTHER", + "type": "other" + }, + { + "name": "ComponentDataKind: SOURCE_CODE", + "type": "source-code" + } + ], + "name": "dummy", + "type": "library" + } + ], + "dependencies": [ + { + "ref": "dummy" + } + ], + "metadata": { + "timestamp": "2023-01-07T13:44:32.312678+00:00" + }, + "properties": [ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + } + ], + "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac", + "version": 1, + "$schema": "http://cyclonedx.org/schema/bom-1.7.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.7" +} \ No newline at end of file diff --git a/tests/_data/snapshots/enum_ComponentDataKind-1.7.xml.bin b/tests/_data/snapshots/enum_ComponentDataKind-1.7.xml.bin new file mode 100644 index 00000000..d5078771 --- /dev/null +++ b/tests/_data/snapshots/enum_ComponentDataKind-1.7.xml.bin @@ -0,0 +1,38 @@ + + + + 2023-01-07T13:44:32.312678+00:00 + + + + dummy + + configuration + ComponentDataKind: CONFIGURATION + + + dataset + ComponentDataKind: DATASET + + + definition + ComponentDataKind: DEFINITION + + + other + ComponentDataKind: OTHER + + + source-code + ComponentDataKind: SOURCE_CODE + + + + + + + + val1 + val2 + + diff --git a/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.5.json.bin b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.5.json.bin new file mode 100644 index 00000000..aacfd208 --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.5.json.bin @@ -0,0 +1,149 @@ +{ + "components": [ + { + "bom-ref": "data-full", + "data": [ + { + "bom-ref": "data-comp-full", + "classification": "public", + "contents": { + "attachment": { + "content": "aGVsbG8gd29ybGQ=", + "contentType": "text/plain", + "encoding": "base64" + }, + "properties": [ + { + "name": "format", + "value": "csv" + } + ], + "url": "https://example.com/datasets/training-v1.csv" + }, + "description": "Training dataset for the primary classifier, version 1.", + "governance": { + "custodians": [ + { + "organization": { + "contact": [ + { + "email": "someone@somewhere.tld", + "name": "A N Other", + "phone": "+44 (0)1234 567890" + }, + { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + ], + "name": "CycloneDX", + "url": [ + "https://cyclonedx.org", + "https://cyclonedx.org/docs" + ] + } + }, + { + "contact": { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + } + ], + "owners": [ + { + "contact": { + "email": "someone@somewhere.tld", + "name": "A N Other", + "phone": "+44 (0)1234 567890" + } + }, + { + "contact": { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + } + ], + "stewards": [ + { + "organization": { + "contact": [ + { + "email": "someone@somewhere.tld", + "name": "A N Other", + "phone": "+44 (0)1234 567890" + }, + { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + ], + "name": "CycloneDX", + "url": [ + "https://cyclonedx.org", + "https://cyclonedx.org/docs" + ] + } + } + ] + }, + "graphics": { + "collection": [ + { + "image": { + "content": "ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ==", + "contentType": "image/png", + "encoding": "base64" + }, + "name": "class-distribution" + }, + { + "image": { + "content": "ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ==", + "contentType": "image/png", + "encoding": "base64" + }, + "name": "feature\ncorrelation" + } + ], + "description": "Data distribution plots,\nmulti-line" + }, + "name": "training-dataset-v1", + "sensitiveData": [ + "PII", + "financial" + ], + "type": "dataset" + } + ], + "name": "full-data-component", + "purl": "pkg:pypi/full-data-component@1.0.0", + "type": "data", + "version": "1.0.0" + } + ], + "dependencies": [ + { + "ref": "data-full" + } + ], + "metadata": { + "timestamp": "2023-01-07T13:44:32.312678+00:00" + }, + "properties": [ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + } + ], + "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac", + "version": 1, + "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.5" +} \ No newline at end of file diff --git a/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.5.xml.bin b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.5.xml.bin new file mode 100644 index 00000000..0d7e2bdd --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.5.xml.bin @@ -0,0 +1,109 @@ + + + + 2023-01-07T13:44:32.312678+00:00 + + + + full-data-component + 1.0.0 + pkg:pypi/full-data-component@1.0.0 + + dataset + training-dataset-v1 + + aGVsbG8gd29ybGQ= + https://example.com/datasets/training-v1.csv + + csv + + + public + PII + financial + + Data distribution plots, +multi-line + + + class-distribution + ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ== + + + feature +correlation + ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ== + + + + Training dataset for the primary classifier, version 1. + + + + + CycloneDX + https://cyclonedx.org + https://cyclonedx.org/docs + + A N Other + someone@somewhere.tld + +44 (0)1234 567890 + + + Paul Horton + paul.horton@owasp.org + + + + + + Paul Horton + paul.horton@owasp.org + + + + + + + CycloneDX + https://cyclonedx.org + https://cyclonedx.org/docs + + A N Other + someone@somewhere.tld + +44 (0)1234 567890 + + + Paul Horton + paul.horton@owasp.org + + + + + + + + A N Other + someone@somewhere.tld + +44 (0)1234 567890 + + + + + Paul Horton + paul.horton@owasp.org + + + + + + + + + + + + val1 + val2 + + diff --git a/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.6.json.bin b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.6.json.bin new file mode 100644 index 00000000..a064ba8f --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.6.json.bin @@ -0,0 +1,161 @@ +{ + "components": [ + { + "bom-ref": "data-full", + "data": [ + { + "bom-ref": "data-comp-full", + "classification": "public", + "contents": { + "attachment": { + "content": "aGVsbG8gd29ybGQ=", + "contentType": "text/plain", + "encoding": "base64" + }, + "properties": [ + { + "name": "format", + "value": "csv" + } + ], + "url": "https://example.com/datasets/training-v1.csv" + }, + "description": "Training dataset for the primary classifier, version 1.", + "governance": { + "custodians": [ + { + "organization": { + "address": { + "country": "GB", + "locality": "Cheshire", + "region": "England", + "streetAddress": "100 Main Street" + }, + "contact": [ + { + "email": "someone@somewhere.tld", + "name": "A N Other", + "phone": "+44 (0)1234 567890" + }, + { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + ], + "name": "CycloneDX", + "url": [ + "https://cyclonedx.org", + "https://cyclonedx.org/docs" + ] + } + }, + { + "contact": { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + } + ], + "owners": [ + { + "contact": { + "email": "someone@somewhere.tld", + "name": "A N Other", + "phone": "+44 (0)1234 567890" + } + }, + { + "contact": { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + } + ], + "stewards": [ + { + "organization": { + "address": { + "country": "GB", + "locality": "Cheshire", + "region": "England", + "streetAddress": "100 Main Street" + }, + "contact": [ + { + "email": "someone@somewhere.tld", + "name": "A N Other", + "phone": "+44 (0)1234 567890" + }, + { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + ], + "name": "CycloneDX", + "url": [ + "https://cyclonedx.org", + "https://cyclonedx.org/docs" + ] + } + } + ] + }, + "graphics": { + "collection": [ + { + "image": { + "content": "ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ==", + "contentType": "image/png", + "encoding": "base64" + }, + "name": "class-distribution" + }, + { + "image": { + "content": "ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ==", + "contentType": "image/png", + "encoding": "base64" + }, + "name": "feature\ncorrelation" + } + ], + "description": "Data distribution plots,\nmulti-line" + }, + "name": "training-dataset-v1", + "sensitiveData": [ + "PII", + "financial" + ], + "type": "dataset" + } + ], + "name": "full-data-component", + "purl": "pkg:pypi/full-data-component@1.0.0", + "type": "data", + "version": "1.0.0" + } + ], + "dependencies": [ + { + "ref": "data-full" + } + ], + "metadata": { + "timestamp": "2023-01-07T13:44:32.312678+00:00" + }, + "properties": [ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + } + ], + "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac", + "version": 1, + "$schema": "http://cyclonedx.org/schema/bom-1.6.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.6" +} \ No newline at end of file diff --git a/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.6.xml.bin b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.6.xml.bin new file mode 100644 index 00000000..4ea63862 --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.6.xml.bin @@ -0,0 +1,121 @@ + + + + 2023-01-07T13:44:32.312678+00:00 + + + + full-data-component + 1.0.0 + pkg:pypi/full-data-component@1.0.0 + + dataset + training-dataset-v1 + + aGVsbG8gd29ybGQ= + https://example.com/datasets/training-v1.csv + + csv + + + public + PII + financial + + Data distribution plots, +multi-line + + + class-distribution + ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ== + + + feature +correlation + ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ== + + + + Training dataset for the primary classifier, version 1. + + + + + CycloneDX +
+ GB + England + Cheshire + 100 Main Street +
+ https://cyclonedx.org + https://cyclonedx.org/docs + + A N Other + someone@somewhere.tld + +44 (0)1234 567890 + + + Paul Horton + paul.horton@owasp.org + +
+
+ + + Paul Horton + paul.horton@owasp.org + + +
+ + + + CycloneDX +
+ GB + England + Cheshire + 100 Main Street +
+ https://cyclonedx.org + https://cyclonedx.org/docs + + A N Other + someone@somewhere.tld + +44 (0)1234 567890 + + + Paul Horton + paul.horton@owasp.org + +
+
+
+ + + + A N Other + someone@somewhere.tld + +44 (0)1234 567890 + + + + + Paul Horton + paul.horton@owasp.org + + + +
+
+
+
+ + + + + val1 + val2 + +
diff --git a/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.7.json.bin b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.7.json.bin new file mode 100644 index 00000000..5c1615ab --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.7.json.bin @@ -0,0 +1,161 @@ +{ + "components": [ + { + "bom-ref": "data-full", + "data": [ + { + "bom-ref": "data-comp-full", + "classification": "public", + "contents": { + "attachment": { + "content": "aGVsbG8gd29ybGQ=", + "contentType": "text/plain", + "encoding": "base64" + }, + "properties": [ + { + "name": "format", + "value": "csv" + } + ], + "url": "https://example.com/datasets/training-v1.csv" + }, + "description": "Training dataset for the primary classifier, version 1.", + "governance": { + "custodians": [ + { + "organization": { + "address": { + "country": "GB", + "locality": "Cheshire", + "region": "England", + "streetAddress": "100 Main Street" + }, + "contact": [ + { + "email": "someone@somewhere.tld", + "name": "A N Other", + "phone": "+44 (0)1234 567890" + }, + { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + ], + "name": "CycloneDX", + "url": [ + "https://cyclonedx.org", + "https://cyclonedx.org/docs" + ] + } + }, + { + "contact": { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + } + ], + "owners": [ + { + "contact": { + "email": "someone@somewhere.tld", + "name": "A N Other", + "phone": "+44 (0)1234 567890" + } + }, + { + "contact": { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + } + ], + "stewards": [ + { + "organization": { + "address": { + "country": "GB", + "locality": "Cheshire", + "region": "England", + "streetAddress": "100 Main Street" + }, + "contact": [ + { + "email": "someone@somewhere.tld", + "name": "A N Other", + "phone": "+44 (0)1234 567890" + }, + { + "email": "paul.horton@owasp.org", + "name": "Paul Horton" + } + ], + "name": "CycloneDX", + "url": [ + "https://cyclonedx.org", + "https://cyclonedx.org/docs" + ] + } + } + ] + }, + "graphics": { + "collection": [ + { + "image": { + "content": "ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ==", + "contentType": "image/png", + "encoding": "base64" + }, + "name": "class-distribution" + }, + { + "image": { + "content": "ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ==", + "contentType": "image/png", + "encoding": "base64" + }, + "name": "feature\ncorrelation" + } + ], + "description": "Data distribution plots,\nmulti-line" + }, + "name": "training-dataset-v1", + "sensitiveData": [ + "PII", + "financial" + ], + "type": "dataset" + } + ], + "name": "full-data-component", + "purl": "pkg:pypi/full-data-component@1.0.0", + "type": "data", + "version": "1.0.0" + } + ], + "dependencies": [ + { + "ref": "data-full" + } + ], + "metadata": { + "timestamp": "2023-01-07T13:44:32.312678+00:00" + }, + "properties": [ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + } + ], + "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac", + "version": 1, + "$schema": "http://cyclonedx.org/schema/bom-1.7.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.7" +} \ No newline at end of file diff --git a/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.7.xml.bin b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.7.xml.bin new file mode 100644 index 00000000..549998a6 --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_data_component-1.7.xml.bin @@ -0,0 +1,121 @@ + + + + 2023-01-07T13:44:32.312678+00:00 + + + + full-data-component + 1.0.0 + pkg:pypi/full-data-component@1.0.0 + + dataset + training-dataset-v1 + + aGVsbG8gd29ybGQ= + https://example.com/datasets/training-v1.csv + + csv + + + public + PII + financial + + Data distribution plots, +multi-line + + + class-distribution + ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ== + + + feature +correlation + ZnVsbC1kYXRhLWNvbXBvbmVudC1pbWFnZQ== + + + + Training dataset for the primary classifier, version 1. + + + + + CycloneDX +
+ GB + England + Cheshire + 100 Main Street +
+ https://cyclonedx.org + https://cyclonedx.org/docs + + A N Other + someone@somewhere.tld + +44 (0)1234 567890 + + + Paul Horton + paul.horton@owasp.org + +
+
+ + + Paul Horton + paul.horton@owasp.org + + +
+ + + + CycloneDX +
+ GB + England + Cheshire + 100 Main Street +
+ https://cyclonedx.org + https://cyclonedx.org/docs + + A N Other + someone@somewhere.tld + +44 (0)1234 567890 + + + Paul Horton + paul.horton@owasp.org + +
+
+
+ + + + A N Other + someone@somewhere.tld + +44 (0)1234 567890 + + + + + Paul Horton + paul.horton@owasp.org + + + +
+
+
+
+ + + + + val1 + val2 + +
diff --git a/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.5.json.bin b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.5.json.bin new file mode 100644 index 00000000..8a5ea6a7 --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.5.json.bin @@ -0,0 +1,74 @@ +{ + "components": [ + { + "bom-ref": "data-referenced", + "data": [ + { + "name": "referenced-dataset", + "type": "dataset" + } + ], + "name": "referenced-dataset", + "type": "data", + "version": "1.0.0" + }, + { + "bom-ref": "ml-datasets", + "modelCard": { + "bom-ref": "mc-datasets", + "modelParameters": { + "datasets": [ + { + "bom-ref": "dataset-inline", + "contents": { + "url": "https://example.com/datasets/inline.csv" + }, + "description": "Dataset described in place.", + "name": "inline-dataset", + "type": "dataset" + }, + { + "ref": "data-referenced" + }, + { + "ref": "urn:cdx:3e671687-395b-41f5-a30f-a58921a69b79/1#data-external" + } + ], + "task": "text-classification" + } + }, + "name": "model-with-datasets", + "type": "machine-learning-model", + "version": "1.0.0" + } + ], + "dependencies": [ + { + "ref": "data-referenced" + }, + { + "dependsOn": [ + "data-referenced" + ], + "ref": "ml-datasets" + } + ], + "metadata": { + "timestamp": "2023-01-07T13:44:32.312678+00:00" + }, + "properties": [ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + } + ], + "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac", + "version": 1, + "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.5" +} \ No newline at end of file diff --git a/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.5.xml.bin b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.5.xml.bin new file mode 100644 index 00000000..56b301e4 --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.5.xml.bin @@ -0,0 +1,47 @@ + + + + 2023-01-07T13:44:32.312678+00:00 + + + + referenced-dataset + 1.0.0 + + dataset + referenced-dataset + + + + model-with-datasets + 1.0.0 + + + text-classification + + + dataset + inline-dataset + + https://example.com/datasets/inline.csv + + Dataset described in place. + + data-referenced + urn:cdx:3e671687-395b-41f5-a30f-a58921a69b79/1#data-external + + + + + + + + + + + + + val1 + val2 + + diff --git a/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.6.json.bin b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.6.json.bin new file mode 100644 index 00000000..77da0fc3 --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.6.json.bin @@ -0,0 +1,74 @@ +{ + "components": [ + { + "bom-ref": "data-referenced", + "data": [ + { + "name": "referenced-dataset", + "type": "dataset" + } + ], + "name": "referenced-dataset", + "type": "data", + "version": "1.0.0" + }, + { + "bom-ref": "ml-datasets", + "modelCard": { + "bom-ref": "mc-datasets", + "modelParameters": { + "datasets": [ + { + "bom-ref": "dataset-inline", + "contents": { + "url": "https://example.com/datasets/inline.csv" + }, + "description": "Dataset described in place.", + "name": "inline-dataset", + "type": "dataset" + }, + { + "ref": "data-referenced" + }, + { + "ref": "urn:cdx:3e671687-395b-41f5-a30f-a58921a69b79/1#data-external" + } + ], + "task": "text-classification" + } + }, + "name": "model-with-datasets", + "type": "machine-learning-model", + "version": "1.0.0" + } + ], + "dependencies": [ + { + "ref": "data-referenced" + }, + { + "dependsOn": [ + "data-referenced" + ], + "ref": "ml-datasets" + } + ], + "metadata": { + "timestamp": "2023-01-07T13:44:32.312678+00:00" + }, + "properties": [ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + } + ], + "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac", + "version": 1, + "$schema": "http://cyclonedx.org/schema/bom-1.6.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.6" +} \ No newline at end of file diff --git a/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.6.xml.bin b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.6.xml.bin new file mode 100644 index 00000000..011c6b9d --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.6.xml.bin @@ -0,0 +1,47 @@ + + + + 2023-01-07T13:44:32.312678+00:00 + + + + referenced-dataset + 1.0.0 + + dataset + referenced-dataset + + + + model-with-datasets + 1.0.0 + + + text-classification + + + dataset + inline-dataset + + https://example.com/datasets/inline.csv + + Dataset described in place. + + data-referenced + urn:cdx:3e671687-395b-41f5-a30f-a58921a69b79/1#data-external + + + + + + + + + + + + + val1 + val2 + + diff --git a/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.7.json.bin b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.7.json.bin new file mode 100644 index 00000000..d431b3d5 --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.7.json.bin @@ -0,0 +1,74 @@ +{ + "components": [ + { + "bom-ref": "data-referenced", + "data": [ + { + "name": "referenced-dataset", + "type": "dataset" + } + ], + "name": "referenced-dataset", + "type": "data", + "version": "1.0.0" + }, + { + "bom-ref": "ml-datasets", + "modelCard": { + "bom-ref": "mc-datasets", + "modelParameters": { + "datasets": [ + { + "bom-ref": "dataset-inline", + "contents": { + "url": "https://example.com/datasets/inline.csv" + }, + "description": "Dataset described in place.", + "name": "inline-dataset", + "type": "dataset" + }, + { + "ref": "data-referenced" + }, + { + "ref": "urn:cdx:3e671687-395b-41f5-a30f-a58921a69b79/1#data-external" + } + ], + "task": "text-classification" + } + }, + "name": "model-with-datasets", + "type": "machine-learning-model", + "version": "1.0.0" + } + ], + "dependencies": [ + { + "ref": "data-referenced" + }, + { + "dependsOn": [ + "data-referenced" + ], + "ref": "ml-datasets" + } + ], + "metadata": { + "timestamp": "2023-01-07T13:44:32.312678+00:00" + }, + "properties": [ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + } + ], + "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac", + "version": 1, + "$schema": "http://cyclonedx.org/schema/bom-1.7.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.7" +} \ No newline at end of file diff --git a/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.7.xml.bin b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.7.xml.bin new file mode 100644 index 00000000..e5116104 --- /dev/null +++ b/tests/_data/snapshots/get_bom_v1_5_with_model_card_datasets-1.7.xml.bin @@ -0,0 +1,47 @@ + + + + 2023-01-07T13:44:32.312678+00:00 + + + + referenced-dataset + 1.0.0 + + dataset + referenced-dataset + + + + model-with-datasets + 1.0.0 + + + text-classification + + + dataset + inline-dataset + + https://example.com/datasets/inline.csv + + Dataset described in place. + + data-referenced + urn:cdx:3e671687-395b-41f5-a30f-a58921a69b79/1#data-external + + + + + + + + + + + + + val1 + val2 + + diff --git a/tests/test_enums.py b/tests/test_enums.py index 94d0a99c..04b1c3ee 100644 --- a/tests/test_enums.py +++ b/tests/test_enums.py @@ -43,6 +43,7 @@ ProtocolProperties, RelatedCryptoMaterialProperties, ) +from cyclonedx.model.data import ComponentData from cyclonedx.model.issue import IssueType from cyclonedx.model.license import DisjunctiveLicense from cyclonedx.model.lifecycle import LifecyclePhase, PredefinedLifecycle @@ -118,6 +119,9 @@ RelatedCryptoMaterialState, RelatedCryptoMaterialType, ) +from cyclonedx.model.data import ( # isort:skip + ComponentDataKind, +) from cyclonedx.model.model_card import ( # isort:skip Co2MeasureUnit, EnergyActivity, @@ -1189,6 +1193,34 @@ def test_cases_render_valid(self, of: OutputFormat, sv: SchemaVersion, *_: Any, super()._test_cases_render(bom, of, sv) +@ddt +class TestEnumComponentDataKind(_EnumTestCase): + + @idata(set(chain( + dp_cases_from_xml_schemas(f"./{SCHEMA_NS}simpleType[@name='componentDataTypeEnumeration']"), + dp_cases_from_json_schemas('definitions', 'componentData', 'properties', 'type'), + ))) + def test_knows_value(self, value: str) -> None: + super()._test_knows_value(ComponentDataKind, value) + + @named_data(*(d for d in NAMED_OF_SV if d[2] >= SchemaVersion.V1_5)) + def test_cases_render_valid(self, of: OutputFormat, sv: SchemaVersion, *_: Any, **__: Any) -> None: + # CycloneDX 1.5's XSD only allows a single `data` element per component + # (fixed to `unbounded` from 1.6 onwards) -- so only exercise one kind there. + kinds = list(ComponentDataKind)[:1] if (of, sv) == (OutputFormat.XML, SchemaVersion.V1_5) \ + else list(ComponentDataKind) + bom = _make_bom(components=[ + Component( + name='dummy', type=ComponentType.LIBRARY, bom_ref='dummy', + data=[ + ComponentData(type=cdk, name=f'ComponentDataKind: {cdk.name}') + for cdk in kinds + ] + ) + ]) + super()._test_cases_render(bom, of, sv) + + # add new test cases above this line diff --git a/tests/test_model_component.py b/tests/test_model_component.py index dc7704d7..5191afc6 100644 --- a/tests/test_model_component.py +++ b/tests/test_model_component.py @@ -28,6 +28,7 @@ XsUri, ) from cyclonedx.model.component import Commit, Component, ComponentType, Diff, Patch, PatchClassification, Pedigree +from cyclonedx.model.data import ComponentData, ComponentDataKind from cyclonedx.model.issue import IssueClassification, IssueType from tests import reorder from tests._data.models import ( @@ -329,6 +330,24 @@ def test_nested_components_2(self) -> None: self.assertEqual(3, len(list(comp_b.iter_all_nested_components(include_self=True)))) self.assertEqual(2, len(list(comp_b.iter_all_nested_components(include_self=False)))) + def test_data(self) -> None: + data_a = ComponentData(type=ComponentDataKind.DATASET, name='a') + data_b = ComponentData(type=ComponentDataKind.OTHER, name='b') + + self.assertEqual(0, len(Component(name='c').data)) + + comp = Component(name='c', type=ComponentType.DATA, data=[data_b, data_a]) + self.assertListEqual([data_a, data_b], list(comp.data)) + + comp.data = [data_b] + self.assertListEqual([data_b], list(comp.data)) + + def test_data_affects_equality(self) -> None: + data = ComponentData(type=ComponentDataKind.DATASET, name='a') + + self.assertEqual(Component(name='c', data=[data]), Component(name='c', data=[data])) + self.assertNotEqual(Component(name='c', data=[data]), Component(name='c')) + class TestModelDiff(TestCase): diff --git a/tests/test_model_component_data.py b/tests/test_model_component_data.py new file mode 100644 index 00000000..2d7e85d3 --- /dev/null +++ b/tests/test_model_component_data.py @@ -0,0 +1,451 @@ +# This file is part of CycloneDX Python Library +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) OWASP Foundation. All Rights Reserved. + +from unittest import TestCase + +from cyclonedx.exception.model import InvalidValueException, MutuallyExclusivePropertiesException +from cyclonedx.model import AttachedText, Property, XsUri +from cyclonedx.model.bom_ref import BomRef +from cyclonedx.model.contact import OrganizationalContact, OrganizationalEntity +from cyclonedx.model.data import ( + ComponentData, + ComponentDataKind, + DataContents, + DataGovernance, + DataGovernanceResponsibleParty, + DatasetReference, +) +from cyclonedx.model.graphics import Graphic, GraphicsCollection +from tests import reorder + + +class TestComponentDataKind(TestCase): + + def test_all_values_exist(self) -> None: + self.assertEqual( + { + ComponentDataKind.SOURCE_CODE.value, + ComponentDataKind.CONFIGURATION.value, + ComponentDataKind.DATASET.value, + ComponentDataKind.DEFINITION.value, + ComponentDataKind.OTHER.value, + }, + { + 'source-code', + 'configuration', + 'dataset', + 'definition', + 'other', + }, + ) + + +class TestDataContents(TestCase): + + def test_defaults(self) -> None: + obj = DataContents() + + self.assertIsNone(obj.attachment) + self.assertIsNone(obj.url) + self.assertEqual(len(obj.properties), 0) + + def test_constructor(self) -> None: + attachment = AttachedText(content='dGVzdA==') + url = XsUri('https://example.org/dataset.csv') + prop = Property(name='format', value='csv') + + obj = DataContents( + attachment=attachment, + url=url, + properties=[prop], + ) + + self.assertEqual(obj.attachment, attachment) + self.assertEqual(obj.url, url) + self.assertIn(prop, obj.properties) + + def test_property_setters(self) -> None: + obj = DataContents() + + attachment = AttachedText(content='dGVzdA==') + url = XsUri('https://example.org/dataset.csv') + obj.attachment = attachment + obj.url = url + + self.assertEqual(obj.attachment, attachment) + self.assertEqual(obj.url, url) + + def test_sorted_properties(self) -> None: + prop_a = Property(name='a', value='1') + prop_b = Property(name='b', value='2') + + obj = DataContents(properties=[prop_b, prop_a]) + + self.assertEqual( + list(obj.properties), + [prop_a, prop_b], + ) + + def test_equality(self) -> None: + self.assertEqual( + DataContents(url=XsUri('https://example.org/a.csv')), + DataContents(url=XsUri('https://example.org/a.csv')), + ) + + def test_inequality(self) -> None: + self.assertNotEqual( + DataContents(url=XsUri('https://example.org/a.csv')), + DataContents(url=XsUri('https://example.org/b.csv')), + ) + + def test_comparison(self) -> None: + first = DataContents(url=XsUri('https://example.org/a.csv')) + second = DataContents(url=XsUri('https://example.org/b.csv')) + + self.assertTrue(first < second) + + def test_hash(self) -> None: + self.assertEqual( + hash(DataContents(url=XsUri('https://example.org/a.csv'))), + hash(DataContents(url=XsUri('https://example.org/a.csv'))), + ) + + def test_repr(self) -> None: + self.assertEqual( + repr(DataContents()), + '', + ) + + +class TestDataGovernanceResponsibleParty(TestCase): + + def test_requires_organization_or_contact(self) -> None: + with self.assertRaises(MutuallyExclusivePropertiesException): + DataGovernanceResponsibleParty() + + def test_organization_and_contact_are_mutually_exclusive(self) -> None: + with self.assertRaises(MutuallyExclusivePropertiesException): + DataGovernanceResponsibleParty( + organization=OrganizationalEntity(name='DataCorp'), + contact=OrganizationalContact(name='Jane Doe'), + ) + + def test_constructor_organization(self) -> None: + org = OrganizationalEntity(name='DataCorp') + + obj = DataGovernanceResponsibleParty(organization=org) + + self.assertEqual(obj.organization, org) + self.assertIsNone(obj.contact) + + def test_constructor_contact(self) -> None: + contact = OrganizationalContact(name='Jane Doe') + + obj = DataGovernanceResponsibleParty(contact=contact) + + self.assertEqual(obj.contact, contact) + self.assertIsNone(obj.organization) + + def test_property_setters(self) -> None: + org = OrganizationalEntity(name='DataCorp') + contact = OrganizationalContact(name='Jane Doe') + obj = DataGovernanceResponsibleParty(organization=org) + + with self.assertRaises(MutuallyExclusivePropertiesException): + obj.contact = contact + self.assertIsNone(obj.contact) + + # switching is possible by unsetting first + obj.organization = None + obj.contact = contact + self.assertIsNone(obj.organization) + self.assertEqual(obj.contact, contact) + + def test_equality(self) -> None: + org = OrganizationalEntity(name='DataCorp') + + self.assertEqual( + DataGovernanceResponsibleParty(organization=org), + DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='DataCorp')), + ) + + def test_inequality(self) -> None: + self.assertNotEqual( + DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='DataCorp')), + DataGovernanceResponsibleParty(contact=OrganizationalContact(name='Jane Doe')), + ) + + def test_comparison(self) -> None: + first = DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='A')) + second = DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='B')) + + self.assertTrue(first < second) + + def test_hash(self) -> None: + org = OrganizationalEntity(name='DataCorp') + + self.assertEqual( + hash(DataGovernanceResponsibleParty(organization=org)), + hash(DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='DataCorp'))), + ) + + def test_repr(self) -> None: + self.assertEqual( + repr(DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='DataCorp'))), + '', + ) + + +class TestDataGovernance(TestCase): + + def test_defaults(self) -> None: + obj = DataGovernance() + + self.assertEqual(len(obj.custodians), 0) + self.assertEqual(len(obj.stewards), 0) + self.assertEqual(len(obj.owners), 0) + + def test_constructor(self) -> None: + custodian = DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='Custodian')) + steward = DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='Steward')) + owner = DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='Owner')) + + obj = DataGovernance( + custodians=[custodian], + stewards=[steward], + owners=[owner], + ) + + self.assertIn(custodian, obj.custodians) + self.assertIn(steward, obj.stewards) + self.assertIn(owner, obj.owners) + + def test_sorted_owners(self) -> None: + owner_a = DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='A')) + owner_b = DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='B')) + + obj = DataGovernance(owners=[owner_b, owner_a]) + + self.assertEqual( + list(obj.owners), + [owner_a, owner_b], + ) + + def test_equality(self) -> None: + self.assertEqual( + DataGovernance(), + DataGovernance(), + ) + + def test_comparison(self) -> None: + self.assertTrue( + DataGovernance() <= DataGovernance() + ) + + def test_hash(self) -> None: + self.assertEqual( + hash(DataGovernance()), + hash(DataGovernance()), + ) + + def test_repr(self) -> None: + self.assertEqual( + repr(DataGovernance()), + '', + ) + + +class TestComponentData(TestCase): + + def test_defaults(self) -> None: + obj = ComponentData(type=ComponentDataKind.DATASET) + + self.assertEqual(obj.type, ComponentDataKind.DATASET) + self.assertIsNone(obj.name) + self.assertIsNone(obj.contents) + self.assertIsNone(obj.classification) + self.assertEqual(len(obj.sensitive_data), 0) + self.assertIsNone(obj.graphics) + self.assertIsNone(obj.description) + self.assertIsNone(obj.governance) + self.assertIsNone(obj.bom_ref.value) + + def test_constructor(self) -> None: + contents = DataContents(url=XsUri('https://example.org/dataset.csv')) + graphics = GraphicsCollection(collection=[Graphic(name='chart')]) + governance = DataGovernance( + owners=[DataGovernanceResponsibleParty(organization=OrganizationalEntity(name='DataCorp'))] + ) + + obj = ComponentData( + type=ComponentDataKind.DATASET, + name='example-dataset', + contents=contents, + classification='public', + sensitive_data=['PII'], + graphics=graphics, + description='Sample dataset', + governance=governance, + bom_ref='data-1', + ) + + self.assertEqual(obj.type, ComponentDataKind.DATASET) + self.assertEqual(obj.name, 'example-dataset') + self.assertEqual(obj.contents, contents) + self.assertEqual(obj.classification, 'public') + self.assertIn('PII', obj.sensitive_data) + self.assertEqual(obj.graphics, graphics) + self.assertEqual(obj.description, 'Sample dataset') + self.assertEqual(obj.governance, governance) + self.assertEqual(obj.bom_ref.value, 'data-1') + + def test_property_setters(self) -> None: + obj = ComponentData(type=ComponentDataKind.DATASET) + + obj.type = ComponentDataKind.CONFIGURATION + obj.name = 'renamed' + obj.classification = 'internal' + obj.description = 'updated description' + + self.assertEqual(obj.type, ComponentDataKind.CONFIGURATION) + self.assertEqual(obj.name, 'renamed') + self.assertEqual(obj.classification, 'internal') + self.assertEqual(obj.description, 'updated description') + + def test_sorted_sensitive_data(self) -> None: + obj = ComponentData(type=ComponentDataKind.DATASET, sensitive_data=['PII', 'PHI']) + + self.assertEqual( + list(obj.sensitive_data), + sorted(['PII', 'PHI']), + ) + + def test_sort(self) -> None: + expected_order = [1, 0] + items = [ + ComponentData(type=ComponentDataKind.DATASET, name='b'), + ComponentData(type=ComponentDataKind.DATASET, name='a'), + ] + expected_items = reorder(items, expected_order) + sorted_items = sorted(items) + self.assertListEqual(sorted_items, expected_items) + + def test_equality(self) -> None: + self.assertEqual( + ComponentData(type=ComponentDataKind.DATASET, name='a'), + ComponentData(type=ComponentDataKind.DATASET, name='a'), + ) + + def test_inequality(self) -> None: + self.assertNotEqual( + ComponentData(type=ComponentDataKind.DATASET, name='a'), + ComponentData(type=ComponentDataKind.DATASET, name='b'), + ) + + def test_comparison(self) -> None: + first = ComponentData(type=ComponentDataKind.DATASET, name='a') + second = ComponentData(type=ComponentDataKind.DATASET, name='b') + + self.assertTrue(first < second) + self.assertTrue(first <= second) + self.assertTrue(second >= first) + + def test_hash(self) -> None: + self.assertEqual( + hash(ComponentData(type=ComponentDataKind.DATASET, name='a')), + hash(ComponentData(type=ComponentDataKind.DATASET, name='a')), + ) + + def test_bom_ref(self) -> None: + self.assertEqual('data-1', ComponentData(type=ComponentDataKind.DATASET, bom_ref='data-1').bom_ref.value) + bom_ref = BomRef('data-2') + self.assertIs(bom_ref, ComponentData(type=ComponentDataKind.DATASET, bom_ref=bom_ref).bom_ref) + + def test_inequality_bom_ref(self) -> None: + self.assertNotEqual( + ComponentData(type=ComponentDataKind.DATASET, bom_ref='a'), + ComponentData(type=ComponentDataKind.DATASET, bom_ref='b'), + ) + + def test_repr(self) -> None: + self.assertEqual( + repr(ComponentData(type=ComponentDataKind.DATASET, name='example', bom_ref='data-1')), + " name='example'>", + ) + + +class TestDatasetReference(TestCase): + + def test_constructor(self) -> None: + bom_ref = BomRef('data-1') + uri = XsUri('urn:cdx:3e671687-395b-41f5-a30f-a58921a69b79/1#data-1') + + self.assertEqual('data-1', DatasetReference(ref='data-1').ref) + self.assertIs(bom_ref, DatasetReference(ref=bom_ref).ref) + self.assertIs(uri, DatasetReference(ref=uri).ref) + + def test_property_setters(self) -> None: + obj = DatasetReference(ref='a') + obj.ref = 'b' + self.assertEqual('b', obj.ref) + + def test_empty_ref_is_rejected(self) -> None: + with self.assertRaises(InvalidValueException): + DatasetReference(ref='') + with self.assertRaises(InvalidValueException): + DatasetReference(ref=XsUri('')) + obj = DatasetReference(ref='a') + with self.assertRaises(InvalidValueException): + obj.ref = '' + self.assertEqual('a', obj.ref) + + def test_bom_ref_without_value_is_accepted(self) -> None: + # the value may be assigned later, when the BOM is serialized + self.assertEqual('', str(DatasetReference(ref=BomRef()).ref)) + + def test_equality(self) -> None: + self.assertEqual(DatasetReference(ref='a'), DatasetReference(ref='a')) + self.assertEqual(DatasetReference(ref='a'), DatasetReference(ref=BomRef('a'))) + self.assertNotEqual(DatasetReference(ref='a'), DatasetReference(ref='b')) + self.assertNotEqual(DatasetReference(ref='a'), 'a') + + def test_comparison(self) -> None: + first = DatasetReference(ref='a') + second = DatasetReference(ref='b') + + self.assertTrue(first < second) + self.assertTrue(first <= second) + self.assertTrue(second >= first) + + def test_comparison_with_component_data(self) -> None: + reference = DatasetReference(ref='a') + data = ComponentData(type=ComponentDataKind.DATASET, name='z') + + # inline data sorts before references, regardless of operand order + self.assertTrue(data < reference) + self.assertTrue(data <= reference) + self.assertTrue(reference >= data) + self.assertFalse(reference < data) + self.assertFalse(reference <= data) + self.assertFalse(data >= reference) + self.assertListEqual([data, reference], sorted([reference, data])) + + def test_hash(self) -> None: + self.assertEqual(hash(DatasetReference(ref='a')), hash(DatasetReference(ref=BomRef('a')))) + + def test_repr(self) -> None: + self.assertEqual("", repr(DatasetReference(ref='a'))) diff --git a/tests/test_model_model_card.py b/tests/test_model_model_card.py index c7b425ef..38545698 100644 --- a/tests/test_model_model_card.py +++ b/tests/test_model_model_card.py @@ -19,6 +19,7 @@ from cyclonedx.model import ExternalReference, ExternalReferenceType, Property from cyclonedx.model.contact import OrganizationalEntity +from cyclonedx.model.data import ComponentData, ComponentDataKind, DatasetReference from cyclonedx.model.model_card import ( Approach, Co2Measure, @@ -243,9 +244,43 @@ def test_property_setters(self) -> None: self.assertEqual(obj.architecture_family, 'cnn') self.assertEqual(obj.model_architecture, 'resnet') - def test_dataset_not_supported(self) -> None: - with self.assertRaises(NotImplementedError): - ModelParameters(datasets=['dataset']) + def test_datasets(self) -> None: + inline = ComponentData(type=ComponentDataKind.DATASET, name='inline') + reference = DatasetReference(ref='data-1') + + obj = ModelParameters(datasets=[reference, inline]) + + self.assertEqual(len(obj.datasets), 2) + self.assertIn(inline, obj.datasets) + self.assertIn(reference, obj.datasets) + + def test_datasets_default_and_setter(self) -> None: + obj = ModelParameters() + self.assertEqual(len(obj.datasets), 0) + + reference = DatasetReference(ref='data-1') + obj.datasets = [reference] + self.assertEqual(list(obj.datasets), [reference]) + + def test_datasets_sort_inline_before_references(self) -> None: + inline_a = ComponentData(type=ComponentDataKind.DATASET, name='a') + inline_b = ComponentData(type=ComponentDataKind.DATASET, name='b') + reference_a = DatasetReference(ref='a') + reference_b = DatasetReference(ref='b') + + obj = ModelParameters(datasets=[reference_b, inline_b, reference_a, inline_a]) + + self.assertListEqual([inline_a, inline_b, reference_a, reference_b], list(obj.datasets)) + + def test_datasets_affect_equality(self) -> None: + self.assertEqual( + ModelParameters(datasets=[DatasetReference(ref='a')]), + ModelParameters(datasets=[DatasetReference(ref='a')]), + ) + self.assertNotEqual( + ModelParameters(datasets=[DatasetReference(ref='a')]), + ModelParameters(datasets=[DatasetReference(ref='b')]), + ) def test_inputs_outputs_keep_order_and_duplicates(self) -> None: a = InputOutputMLParameters(format='A')