Exemple #1
0
    def test_entity(self):
        my_user = User(id="my_user_id")
        filter_definition = {"sub_entity": {"eq": my_user}}
        expected_filter = {"sub_entity__eq": "my_user_id"}

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
    def test_get_and_set_resource_value(self):
        # an example: get and set a resource value
        from mbed_cloud.foundation import Device
        from mbed_cloud import ApiFilter
        from mbed_cloud.foundation.enums import DeviceStateEnum
        from mbed_cloud import ConnectAPI

        # Use the Foundation interface to find a registered device.
        api_filter = ApiFilter()
        api_filter.add_filter("state", "eq", DeviceStateEnum.REGISTERED)
        device = Device().list(max_results=2, filter=api_filter).next()

        # Use the Legacy interface to find resources
        connect_api = ConnectAPI()

        # Find an observable resource
        for resource in connect_api.list_resources(device.id):
            if resource.observable:
                break

        # Set a resource value
        connect_api.set_resource_value(device.id, resource.path, "12")

        # Get a resource value
        value = connect_api.get_resource_value(device.id, resource.path)
        print("Device %s, path %s, current value: %s" %(device.id, resource.path, value))
        # end of example

        connect_api.stop_notifications()
Exemple #3
0
    def test_rename(self):
        filter_definition = {"SDK_name": {"eq": "Badger"}}
        renames = {"SDK_name": "API_name"}
        expected_filter = {"API_name__eq": "Badger"}

        api_filter = ApiFilter(filter_definition, renames)
        self.assertEqual(expected_filter, api_filter.to_api())
    def list(self,
             filter=None,
             order=None,
             max_results=None,
             page_size=None,
             include=None):
        """Get metadata of all dark theme images.

        `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-images/dark>`_.
        
        :param filter: Filtering when listing entities is not supported by the API for this
            entity.
        :type filter: mbed_cloud.client.api_filter.ApiFilter
        
        :param order: The order of the records based on creation time, ASC or DESC. Default
            value is ASC
        :type order: str
        
        :param max_results: Total maximum number of results to retrieve
        :type max_results: int
        
        :param page_size: The number of results to return for each page.
        :type page_size: int
        
        :param include: Comma separated additional data to return.
        :type include: str
        
        :return: An iterator object which yields instances of an entity.
        :rtype: mbed_cloud.pagination.PaginatedResponse(DarkThemeImage)
        """

        from mbed_cloud.foundation._custom_methods import paginate
        from mbed_cloud.foundation import DarkThemeImage
        from mbed_cloud import ApiFilter

        # Be permissive and accept an instance of a dictionary as this was how the Legacy interface worked.
        if isinstance(filter, dict):
            filter = ApiFilter(filter_definition=filter,
                               field_renames=DarkThemeImage._renames_to_api)
        # The preferred method is an ApiFilter instance as this should be easier to use.
        elif isinstance(filter, ApiFilter):
            # If filter renames have not be defined then configure the ApiFilter so that any renames
            # performed by the SDK are reversed when the query parameters are created.
            if filter.field_renames is None:
                filter.field_renames = DarkThemeImage._renames_to_api
        elif filter is not None:
            raise TypeError(
                "The 'filter' parameter may be either 'dict' or 'ApiFilter'.")

        return paginate(
            self=self,
            foreign_key=DarkThemeImage,
            filter=filter,
            order=order,
            max_results=max_results,
            page_size=page_size,
            include=include,
            wraps=self._paginate_list,
        )
Exemple #5
0
    def test_list_type(self):
        filter_definition = {"name": {"in": ["Badger", "Gopher"]}}
        expected_filter = {"name__in": "Badger,Gopher"}
        expected_query_string = "name__in=Badger,Gopher"

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
        self.assertEqual(expected_query_string, api_filter.to_query_string())
Exemple #6
0
    def test_string_type(self):
        filter_definition = {"name": {"eq": "Badger"}}
        expected_filter = {"name__eq": "Badger"}
        expected_query_string = "name__eq=Badger"

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
        self.assertEqual(expected_query_string, api_filter.to_query_string())
Exemple #7
0
    def test_list_of_entities_filter(self):
        user_one = User(id="user1")
        user_two = User(id="user2")
        filter_definition = {"sub_entity": {"in": [user_one, user_two]}}
        expected_filter = {"sub_entity__in": "user1,user2"}

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
Exemple #8
0
def device_filter_helper_getter(self):
    """Return the configured campaign device filter.

    :param self: Instance of the entity for which this is a custom method.
    :type self: mbed_cloud.foundation.UpdateCampaign

    :rtype: mbed_cloud.client.api_filter.ApiFilter
    """
    return ApiFilter(filter_definition=self._device_filter_helper.value,
                     field_renames=Device._renames_to_api)
Exemple #9
0
    def test_nested_list_filter(self):
        filter_definition = {
            "name": {
                "in": ["Badger", [17, 20.5], True,
                       datetime(2019, 1, 1), None]
            }
        }
        expected_filter = {
            "name__in": "Badger,17,20.5,true,2019-01-01T00:00:00Z,null"
        }

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
Exemple #10
0
    def test_legacy_filter(self):
        filter_definition = {
            "created_at": {
                "$gte": datetime(2019, 1, 1),
                "$lte": date(2019, 12, 31),
            },
            "colour": {
                "$like": "purple"
            },
            "integer": {
                "$neq": 42
            },
            "float": {
                "$neq": 13.98
            },
            "state": {
                "$in": ["OPEN", "CLOSED"]
            },
            "city": {
                "$nin": ["Cambridge", "London"]
            },
            "strange": {
                "$eq": {
                    "hello": "world"
                }
            },
            "done": False,
            "firmware_checksum": None,
        }
        renames = {
            "colour": "API_colour",
            "state": "API_state",
            "strange": "API_strange",
            "firmware_checksum": "API_fw_csum",
        }
        expected_filter = {
            "created_at__gte": "2019-01-01T00:00:00Z",
            "created_at__lte": "2019-12-31",
            "API_colour__like": "purple",
            "integer__neq": 42,
            "float__neq": 13.98,
            "API_state__in": "OPEN,CLOSED",
            "city__nin": "Cambridge,London",
            "API_strange__eq": '{"hello": "world"}',
            "done__eq": "false",
            "API_fw_csum__eq": "null"
        }

        api_filter = ApiFilter(filter_definition, renames)
        self.assertEqual(expected_filter, api_filter.to_api())
    def test_list_entities_with_filters(self):
        from mbed_cloud import SDK
        pelion_dm_sdk = SDK()

        # an example: list entities with filters
        from mbed_cloud import ApiFilter
        from mbed_cloud.foundation.enums import UserStatusEnum

        api_filter = ApiFilter()
        api_filter.add_filter("email", "eq", "*****@*****.**")
        api_filter.add_filter(
            "status", "in", [UserStatusEnum.ACTIVE, UserStatusEnum.ENROLLING])

        for user in pelion_dm_sdk.foundation.user().list(filter=api_filter):
            print("%s (%s): %s" % (user.full_name, user.id, user.email))
    def test_firmware_update_campaign_launch(self):
        from mbed_cloud.foundation import FirmwareManifest

        firmware_manifest = FirmwareManifest().list().first()
        my_manifest_id = firmware_manifest.id

        # an example: firmware update campaign launch
        from datetime import datetime
        from pprint import pprint
        from mbed_cloud import SDK
        from mbed_cloud import ApiFilter

        pelion_dm_sdk = SDK()
        new_campaign = pelion_dm_sdk.foundation.update_campaign(
            root_manifest_id=my_manifest_id,
            name="campaign - " + str(datetime.now()),
            description="Update campaign for prior 2019 devices")

        # Create a filter for all devices created before the 1st of January 2019 so that these devices will have their
        # firmware replaced by the one defined in the manifest.
        api_filter = ApiFilter()
        api_filter.add_filter("created_at", "lte", datetime(2019, 1, 1))
        new_campaign.device_filter_helper = api_filter

        # Create the campaign
        new_campaign.create()

        # Determine the phase of the campaign
        print("Campaign Phase:", new_campaign.phase)

        # Start the campaign
        new_campaign.start()

        # Determine the phase of the campaign
        new_campaign.read()
        print("Campaign Phase:", new_campaign.phase)

        # Print all device metadata related to this campaign
        for campaign_device_metadata in new_campaign.device_metadata():
            pprint(campaign_device_metadata.to_dict())

        # end of example
        new_campaign.stop()
        new_campaign.read()
        print("Campaign Phase:", new_campaign.phase)

        new_campaign.delete()
    def test_certificate_black_listing(self):
        from mbed_cloud.foundation import TrustedCertificate

        # Find a production certificate
        my_certificate = TrustedCertificate().list(filter={
            "device_execution_mode": {
                "neq": 1
            }
        }).first()
        my_cert_id = my_certificate.id
        # Record the original status to revert to its original state at the end
        original_status = TrustedCertificate(id=my_cert_id).read().status

        # an example: certificate black listing
        from mbed_cloud import SDK
        from mbed_cloud import ApiFilter
        from mbed_cloud.foundation.enums import TrustedCertificateStatusEnum

        pelion_dm_sdk = SDK()

        # Set the certificate to inactive
        my_cert = pelion_dm_sdk.foundation.trusted_certificate(
            id=my_cert_id).read()
        my_cert.status = TrustedCertificateStatusEnum.INACTIVE
        my_cert.update()

        # List all devices which have tried to bootstrap
        api_filter = ApiFilter()
        api_filter.add_filter("trusted_certificate_id", "eq", my_cert)

        for device_denial in pelion_dm_sdk.foundation.device_enrollment_denial(
        ).list(filter=api_filter):
            print("Device endpoint name: %s" % device_denial.endpoint_name)
        # end of example

        new_status = my_cert.read().status
        self.assertEqual(TrustedCertificateStatusEnum.INACTIVE, new_status,
                         "Status should have been set to disabled")

        # Revert the certificate to its original status
        my_cert.status = original_status
        my_cert.update()

        end_status = my_cert.read().status
        self.assertEqual(
            original_status, end_status,
            "Status should have been reverted back to its original value")
Exemple #14
0
def device_filter_helper_setter(self, value):
    """Create a campaign device filter from an API Filter

    :param self: Instance of the entity for which this is a custom method.
    :type self: mbed_cloud.foundation.UpdateCampaign
    :param value: Device filter for campaign
    :type value: mbed_cloud.client.api_filter.ApiFilter
    """
    if isinstance(value, dict):
        value = ApiFilter(filter_definition=value,
                          field_renames=Device._renames_to_api)
    elif isinstance(value, ApiFilter):
        value.field_renames = Device._renames_to_api
    elif value is not None:
        raise TypeError("This field may be either 'dict' or 'ApiFilter'.")
    # Store the filter as a dictionary for later retrieval if needed
    self._device_filter_helper.set(value.filter_definition)
    # Render the filter as a string for serialisation to the API
    self.device_filter = value.to_query_string()
Exemple #15
0
    def test_add_filter(self):
        api_filter = ApiFilter()
        self.assertEqual({}, api_filter.to_api())

        api_filter.add_filter("created_at", "gte", datetime(2019, 1, 1))
        expected_filter = {"created_at__gte": "2019-01-01T00:00:00Z"}
        self.assertEqual(expected_filter, api_filter.to_api())

        api_filter.add_filter("created_at", "lte", date(2019, 12, 31))
        expected_filter = {
            "created_at__gte": "2019-01-01T00:00:00Z",
            "created_at__lte": "2019-12-31"
        }
        self.assertEqual(expected_filter, api_filter.to_api())

        api_filter.add_filter("status", "eq", True)
        expected_filter = {
            "created_at__gte": "2019-01-01T00:00:00Z",
            "created_at__lte": "2019-12-31",
            "status__eq": "true"
        }
        expected_query_string = "created_at__gte=2019-01-01T00:00:00Z&created_at__lte=2019-12-31&status__eq=true"
        self.assertEqual(expected_filter, api_filter.to_api())
        self.assertEqual(expected_query_string, api_filter.to_query_string())
Exemple #16
0
    def test_float_type(self):
        filter_definition = {"name": {"gte": -1.7}}
        expected_filter = {"name__gte": -1.7}

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
    def list(self,
             filter=None,
             order=None,
             max_results=None,
             page_size=None,
             include=None):
        """Return list of devices which were denied to bootstrap due to being subjected to blacklisting.

        `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/device-enrollment-denials>`_.

        **API Filters**

        The following filters are supported by the API when listing DeviceEnrollmentDenial entities:

        +------------------------+------+------+------+------+------+------+------+
        | Field                  | eq   | neq  | gte  | lte  | in   | nin  | like |
        +========================+======+======+======+======+======+======+======+
        | endpoint_name          | Y    |      |      |      |      |      |      |
        +------------------------+------+------+------+------+------+------+------+
        | trusted_certificate_id | Y    |      |      |      |      |      |      |
        +------------------------+------+------+------+------+------+------+------+

        **Example Usage**

        .. code-block:: python

            from mbed_cloud.foundation import DeviceEnrollmentDenial
            from mbed_cloud import ApiFilter

            api_filter = ApiFilter()
            api_filter.add_filter("endpoint_name", "eq", <filter value>)
            for device_enrollment_denial in DeviceEnrollmentDenial().list(filter=api_filter):
                print(device_enrollment_denial.endpoint_name)
        
        :param filter: An optional filter to apply when listing entities, please see the
            above **API Filters** table for supported filters.
        :type filter: mbed_cloud.client.api_filter.ApiFilter
        
        :param order: Optional parameter for pagination.
        :type order: str
        
        :param max_results: Total maximum number of results to retrieve
        :type max_results: int
        
        :param page_size: Optional parameter for pagination.
        :type page_size: int
        
        :param include: Comma separated additional data to return.
        :type include: str
        
        :return: An iterator object which yields instances of an entity.
        :rtype: mbed_cloud.pagination.PaginatedResponse(DeviceEnrollmentDenial)
        """

        from mbed_cloud.foundation._custom_methods import paginate
        from mbed_cloud.foundation import DeviceEnrollmentDenial
        from mbed_cloud import ApiFilter

        # Be permissive and accept an instance of a dictionary as this was how the Legacy interface worked.
        if isinstance(filter, dict):
            filter = ApiFilter(
                filter_definition=filter,
                field_renames=DeviceEnrollmentDenial._renames_to_api)
        # The preferred method is an ApiFilter instance as this should be easier to use.
        elif isinstance(filter, ApiFilter):
            # If filter renames have not be defined then configure the ApiFilter so that any renames
            # performed by the SDK are reversed when the query parameters are created.
            if filter.field_renames is None:
                filter.field_renames = DeviceEnrollmentDenial._renames_to_api
        elif filter is not None:
            raise TypeError(
                "The 'filter' parameter may be either 'dict' or 'ApiFilter'.")

        return paginate(
            self=self,
            foreign_key=DeviceEnrollmentDenial,
            filter=filter,
            order=order,
            max_results=max_results,
            page_size=page_size,
            include=include,
            wraps=self._paginate_list,
        )
    def list(self,
             filter=None,
             order=None,
             max_results=None,
             page_size=None,
             include=None):
        """Get certificate issuer configurations.

        `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/certificate-issuer-configurations>`_.

        **API Filters**

        The following filters are supported by the API when listing CertificateIssuerConfig entities:

        +-----------+------+------+------+------+------+------+------+
        | Field     | eq   | neq  | gte  | lte  | in   | nin  | like |
        +===========+======+======+======+======+======+======+======+
        | reference | Y    |      |      |      |      |      |      |
        +-----------+------+------+------+------+------+------+------+

        **Example Usage**

        .. code-block:: python

            from mbed_cloud.foundation import CertificateIssuerConfig
            from mbed_cloud import ApiFilter

            api_filter = ApiFilter()
            api_filter.add_filter("reference", "eq", <filter value>)
            for certificate_issuer_config in CertificateIssuerConfig().list(filter=api_filter):
                print(certificate_issuer_config.reference)
        
        :param filter: An optional filter to apply when listing entities, please see the
            above **API Filters** table for supported filters.
        :type filter: mbed_cloud.client.api_filter.ApiFilter
        
        :param order: The order of the records based on creation time, `ASC` or `DESC`; by
            default `ASC`.
        :type order: str
        
        :param max_results: Total maximum number of results to retrieve
        :type max_results: int
        
        :param page_size: How many objects to retrieve in the page. The minimum limit is 2 and
            the maximum is 1000. Limit values outside of this range are set to the
            closest limit.
        :type page_size: int
        
        :param include: Comma-separated list of data fields to return. Currently supported:
            `total_count`
        :type include: str
        
        :return: An iterator object which yields instances of an entity.
        :rtype: mbed_cloud.pagination.PaginatedResponse(CertificateIssuerConfig)
        """

        from mbed_cloud.foundation._custom_methods import paginate
        from mbed_cloud.foundation import CertificateIssuerConfig
        from mbed_cloud import ApiFilter

        # Be permissive and accept an instance of a dictionary as this was how the Legacy interface worked.
        if isinstance(filter, dict):
            filter = ApiFilter(
                filter_definition=filter,
                field_renames=CertificateIssuerConfig._renames_to_api)
        # The preferred method is an ApiFilter instance as this should be easier to use.
        elif isinstance(filter, ApiFilter):
            # If filter renames have not be defined then configure the ApiFilter so that any renames
            # performed by the SDK are reversed when the query parameters are created.
            if filter.field_renames is None:
                filter.field_renames = CertificateIssuerConfig._renames_to_api
        elif filter is not None:
            raise TypeError(
                "The 'filter' parameter may be either 'dict' or 'ApiFilter'.")

        return paginate(
            self=self,
            foreign_key=CertificateIssuerConfig,
            filter=filter,
            order=order,
            max_results=max_results,
            page_size=page_size,
            include=include,
            wraps=self._paginate_list,
        )
    def devices(self,
                filter=None,
                order=None,
                max_results=None,
                page_size=None,
                include=None):
        """Get a page of devices

        `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/device-groups/{device-group-id}/devices/>`_.

        **API Filters**

        The following filters are supported by the API when listing DeviceGroup entities:

        +---------------------------+------+------+------+------+------+------+------+
        | Field                     | eq   | neq  | gte  | lte  | in   | nin  | like |
        +===========================+======+======+======+======+======+======+======+
        | account_id                | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | auto_update               | Y    | Y    |      |      |      |      |      |
        +---------------------------+------+------+------+------+------+------+------+
        | bootstrap_expiration_date |      |      | Y    | Y    | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | bootstrapped_timestamp    |      |      | Y    | Y    | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | ca_id                     | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | connector_expiration_date |      |      | Y    | Y    | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | created_at                |      |      | Y    | Y    | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | deployed_state            | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | deployment                | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | description               | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | device_class              | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | device_execution_mode     | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | device_key                | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | endpoint_name             | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | endpoint_type             | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | enrolment_list_timestamp  |      |      | Y    | Y    | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | firmware_checksum         | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | host_gateway              | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | id                        | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | manifest                  | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | manifest_timestamp        |      |      | Y    | Y    | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | mechanism                 | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | mechanism_url             | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | name                      | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | serial_number             | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | state                     | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | updated_at                |      |      | Y    | Y    | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+
        | vendor_id                 | Y    | Y    |      |      | Y    | Y    |      |
        +---------------------------+------+------+------+------+------+------+------+

        **Example Usage**

        .. code-block:: python

            from mbed_cloud.foundation import DeviceGroup
            from mbed_cloud import ApiFilter

            api_filter = ApiFilter()
            api_filter.add_filter("account_id", "eq", <filter value>)
            for device in DeviceGroup().devices(filter=api_filter):
                print(device.account_id)
        
        :param filter: An optional filter to apply when listing entities, please see the
            above **API Filters** table for supported filters.
        :type filter: mbed_cloud.client.api_filter.ApiFilter
        
        :param order: The order of the records based on creation time, `ASC` or `DESC`; by
            default `ASC`.
        :type order: str
        
        :param max_results: Total maximum number of results to retrieve
        :type max_results: int
        
        :param page_size: How many objects to retrieve in the page. The minimum limit is 2 and
            the maximum is 1000. Limit values outside of this range are set to the
            closest limit.
        :type page_size: int
        
        :param include: Comma-separated list of data fields to return. Currently supported:
            `total_count`.
        :type include: str
        
        :return: An iterator object which yields instances of an entity.
        :rtype: mbed_cloud.pagination.PaginatedResponse(Device)
        """

        from mbed_cloud.foundation._custom_methods import paginate
        from mbed_cloud.foundation import Device
        from mbed_cloud import ApiFilter

        # Be permissive and accept an instance of a dictionary as this was how the Legacy interface worked.
        if isinstance(filter, dict):
            filter = ApiFilter(filter_definition=filter,
                               field_renames=Device._renames_to_api)
        # The preferred method is an ApiFilter instance as this should be easier to use.
        elif isinstance(filter, ApiFilter):
            # If filter renames have not be defined then configure the ApiFilter so that any renames
            # performed by the SDK are reversed when the query parameters are created.
            if filter.field_renames is None:
                filter.field_renames = Device._renames_to_api
        elif filter is not None:
            raise TypeError(
                "The 'filter' parameter may be either 'dict' or 'ApiFilter'.")

        return paginate(
            self=self,
            foreign_key=Device,
            filter=filter,
            order=order,
            max_results=max_results,
            page_size=page_size,
            include=include,
            wraps=self._paginate_devices,
        )
Exemple #20
0
    def test_missing_operator(self):
        filter_definition = {"name": date(2019, 3, 7)}
        expected_filter = {"name__eq": "2019-03-07"}

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
Exemple #21
0
    def list(self,
             filter=None,
             order="ASC",
             max_results=None,
             page_size=50,
             include=None):
        """Get the details of all users.

        `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/users>`_.

        **API Filters**

        The following filters are supported by the API when listing User entities:

        +----------------+------+------+------+------+------+------+------+
        | Field          | eq   | neq  | gte  | lte  | in   | nin  | like |
        +================+======+======+======+======+======+======+======+
        | email          | Y    |      |      |      |      |      |      |
        +----------------+------+------+------+------+------+------+------+
        | login_profiles | Y    |      |      |      |      |      |      |
        +----------------+------+------+------+------+------+------+------+
        | status         | Y    |      |      |      | Y    | Y    |      |
        +----------------+------+------+------+------+------+------+------+

        **Example Usage**

        .. code-block:: python

            from mbed_cloud.foundation import User
            from mbed_cloud import ApiFilter

            api_filter = ApiFilter()
            api_filter.add_filter("email", "eq", <filter value>)
            for user in User().list(filter=api_filter):
                print(user.email)
        
        :param filter: An optional filter to apply when listing entities, please see the
            above **API Filters** table for supported filters.
        :type filter: mbed_cloud.client.api_filter.ApiFilter
        
        :param order: Record order based on creation time. Acceptable values: ASC, DESC.
            Default: ASC.
        :type order: str
        
        :param max_results: Total maximum number of results to retrieve
        :type max_results: int
        
        :param page_size: The number of results to return (2-1000). Default 50.
        :type page_size: int
        
        :param include: Comma-separated additional data to return. Currently supported:
            total_count.
        :type include: str
        
        :return: An iterator object which yields instances of an entity.
        :rtype: mbed_cloud.pagination.PaginatedResponse(User)
        """

        from mbed_cloud.foundation._custom_methods import paginate
        from mbed_cloud.foundation import User
        from mbed_cloud import ApiFilter

        # Be permissive and accept an instance of a dictionary as this was how the Legacy interface worked.
        if isinstance(filter, dict):
            filter = ApiFilter(filter_definition=filter,
                               field_renames=User._renames_to_api)
        # The preferred method is an ApiFilter instance as this should be easier to use.
        elif isinstance(filter, ApiFilter):
            # If filter renames have not be defined then configure the ApiFilter so that any renames
            # performed by the SDK are reversed when the query parameters are created.
            if filter.field_renames is None:
                filter.field_renames = User._renames_to_api
        elif filter is not None:
            raise TypeError(
                "The 'filter' parameter may be either 'dict' or 'ApiFilter'.")

        return paginate(
            self=self,
            foreign_key=User,
            filter=filter,
            order=order,
            max_results=max_results,
            page_size=page_size,
            include=include,
            wraps=self._paginate_list,
        )
Exemple #22
0
    def test_none(self):
        filter_definition = {"name": {"eq": None}}
        expected_filter = {"name__eq": "null"}

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
Exemple #23
0
    def test_dict_type(self):
        filter_definition = {"name": {"nin": {"Animal": "Badger"}}}
        expected_filter = {"name__nin": '{"Animal": "Badger"}'}

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
Exemple #24
0
    def test_date_type(self):
        filter_definition = {"name": {"eq": date(2019, 3, 7)}}
        expected_filter = {"name__eq": "2019-03-07"}

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
Exemple #25
0
    def device_metadata(self,
                        filter=None,
                        order=None,
                        max_results=None,
                        page_size=None,
                        include=None):
        """List all campaign device metadata

        `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/update-campaigns/{campaign_id}/campaign-device-metadata/>`_.
        
        :param filter: Filtering when listing entities is not supported by the API for this
            entity.
        :type filter: mbed_cloud.client.api_filter.ApiFilter
        
        :param order: ASC or DESC
        :type order: str
        
        :param max_results: Total maximum number of results to retrieve
        :type max_results: int
        
        :param page_size: How many objects to retrieve in the page. The minimum limit is 2 and
            the maximum is 1000. Limit values outside of this range are set to the
            closest limit.
        :type page_size: int
        
        :param include: A comma-separated list of data fields to return. Currently supported:
            total_count
        :type include: str
        
        :return: An iterator object which yields instances of an entity.
        :rtype: mbed_cloud.pagination.PaginatedResponse(CampaignDeviceMetadata)
        """

        from mbed_cloud.foundation._custom_methods import paginate
        from mbed_cloud.foundation import CampaignDeviceMetadata
        from mbed_cloud import ApiFilter

        # Be permissive and accept an instance of a dictionary as this was how the Legacy interface worked.
        if isinstance(filter, dict):
            filter = ApiFilter(
                filter_definition=filter,
                field_renames=CampaignDeviceMetadata._renames_to_api)
        # The preferred method is an ApiFilter instance as this should be easier to use.
        elif isinstance(filter, ApiFilter):
            # If filter renames have not be defined then configure the ApiFilter so that any renames
            # performed by the SDK are reversed when the query parameters are created.
            if filter.field_renames is None:
                filter.field_renames = CampaignDeviceMetadata._renames_to_api
        elif filter is not None:
            raise TypeError(
                "The 'filter' parameter may be either 'dict' or 'ApiFilter'.")

        return paginate(
            self=self,
            foreign_key=CampaignDeviceMetadata,
            filter=filter,
            order=order,
            max_results=max_results,
            page_size=page_size,
            include=include,
            wraps=self._paginate_device_metadata,
        )
Exemple #26
0
    def test_single_list_filter(self):
        filter_definition = {"name": {"in": ["Gopher"]}}
        expected_filter = {"name__in": "Gopher"}

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
Exemple #27
0
    def test_integer_type(self):
        filter_definition = {"name": {"neq": -50}}
        expected_filter = {"name__neq": -50}

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())
    def list(self, filter=None, order=None, max_results=None, page_size=None, include=None):
        """List all images

        `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/firmware-images/>`_.

        **API Filters**

        The following filters are supported by the API when listing FirmwareImage entities:

        +-------------------+------+------+------+------+------+------+------+
        | Field             | eq   | neq  | gte  | lte  | in   | nin  | like |
        +===================+======+======+======+======+======+======+======+
        | created_at        |      |      | Y    | Y    | Y    | Y    |      |
        +-------------------+------+------+------+------+------+------+------+
        | datafile_checksum | Y    | Y    |      |      | Y    | Y    |      |
        +-------------------+------+------+------+------+------+------+------+
        | datafile_size     | Y    | Y    |      |      | Y    | Y    |      |
        +-------------------+------+------+------+------+------+------+------+
        | datafile_url      | Y    | Y    |      |      | Y    | Y    |      |
        +-------------------+------+------+------+------+------+------+------+
        | description       | Y    | Y    |      |      | Y    | Y    |      |
        +-------------------+------+------+------+------+------+------+------+
        | id                | Y    | Y    |      |      | Y    | Y    |      |
        +-------------------+------+------+------+------+------+------+------+
        | name              | Y    | Y    |      |      | Y    | Y    |      |
        +-------------------+------+------+------+------+------+------+------+
        | updated_at        |      |      | Y    | Y    | Y    | Y    |      |
        +-------------------+------+------+------+------+------+------+------+

        **Example Usage**

        .. code-block:: python

            from mbed_cloud.foundation import FirmwareImage
            from mbed_cloud import ApiFilter

            api_filter = ApiFilter()
            api_filter.add_filter("created_at", "in", <filter value>)
            for firmware_image in FirmwareImage().list(filter=api_filter):
                print(firmware_image.created_at)
        
        :param filter: An optional filter to apply when listing entities, please see the
            above **API Filters** table for supported filters.
        :type filter: mbed_cloud.client.api_filter.ApiFilter
        
        :param order: ASC or DESC
        :type order: str
        
        :param max_results: Total maximum number of results to retrieve
        :type max_results: int
        
        :param page_size: How many objects to retrieve in the page. The minimum limit is 2 and
            the maximum is 1000. Limit values outside of this range are set to the
            closest limit.
        :type page_size: int
        
        :param include: A comma-separated list of data fields to return. Currently supported:
            total_count
        :type include: str
        
        :return: An iterator object which yields instances of an entity.
        :rtype: mbed_cloud.pagination.PaginatedResponse(FirmwareImage)
        """

        from mbed_cloud.foundation._custom_methods import paginate
        from mbed_cloud.foundation import FirmwareImage
        from mbed_cloud import ApiFilter

        # Be permissive and accept an instance of a dictionary as this was how the Legacy interface worked.
        if isinstance(filter, dict):
            filter = ApiFilter(filter_definition=filter, field_renames=FirmwareImage._renames_to_api)
        # The preferred method is an ApiFilter instance as this should be easier to use.
        elif isinstance(filter, ApiFilter):
            # If filter renames have not be defined then configure the ApiFilter so that any renames
            # performed by the SDK are reversed when the query parameters are created.
            if filter.field_renames is None:
                filter.field_renames = FirmwareImage._renames_to_api
        elif filter is not None:
            raise TypeError("The 'filter' parameter may be either 'dict' or 'ApiFilter'.")

        return paginate(
            self=self,
            foreign_key=FirmwareImage,
            filter=filter,
            order=order,
            max_results=max_results,
            page_size=page_size,
            include=include,
            wraps=self._paginate_list,
        )
Exemple #29
0
    def test_boolean_type(self):
        filter_definition = {"name": {"like": True}}
        expected_filter = {"name__like": "true"}

        api_filter = ApiFilter(filter_definition)
        self.assertEqual(expected_filter, api_filter.to_api())