Best Python code snippet using avocado_python
alexa_entity.py
Source:alexa_entity.py  
...11from typing import Any, Dict, List, Optional, Text, Tuple, TypedDict, Union12from alexapy import AlexaAPI, AlexaLogin, hide_serial13from homeassistant.helpers.update_coordinator import DataUpdateCoordinator14_LOGGER = logging.getLogger(__name__)15def has_capability(16    appliance: Dict[Text, Any], interface_name: Text, property_name: Text17) -> bool:18    """Determine if an appliance from the Alexa network details offers a particular interface with enough support that is worth adding to Home Assistant.19    Args:20        appliance(Dict[Text, Any]): An appliance from a call to AlexaAPI.get_network_details21        interface_name(Text): One of the interfaces documented by the Alexa Smart Home Skills API22        property_name(Text): The property that matches the interface name.23    """24    for cap in appliance["capabilities"]:25        props = cap.get("properties")26        if (27            cap["interfaceName"] == interface_name28            and props29            and (props["retrievable"] or props["proactivelyReported"])30        ):31            for prop in props["supported"]:32                if prop["name"] == property_name:33                    return True34    return False35def is_hue_v1(appliance: Dict[Text, Any]) -> bool:36    """Determine if an appliance is managed via the Philips Hue v1 Hub.37    This check catches old Philips Hue bulbs and hubs, but critically, it also catches things pretending to be older38    Philips Hue bulbs and hubs. This includes things exposed by HA to Alexa using the emulated_hue integration.39    """40    return appliance.get("manufacturerName") == "Royal Philips Electronics"41def is_local(appliance: Dict[Text, Any]) -> bool:42    """Test whether locally connected.43    This is mainly present to prevent loops with the official Alexa integration.44    There is probably a better way to prevent that, but this works.45    """46    if appliance.get("connectedVia"):47        # connectedVia is a flag that determines which Echo devices holds the connection. Its blank for48        # skill derived devices and includes an Echo name for zigbee and local devices.49        return True50    # This catches the Echo/AVS devices. connectedVia isn't reliable in this case.51    # Only the first appears to get that set.52    if "ALEXA_VOICE_ENABLED" in appliance.get("applianceTypes", []):53        namespace = appliance.get("driverIdentity", {}).get("namespace", "")54        return namespace and namespace != "SKILL"55    # Zigbee devices are guaranteed to be local and have a particular pattern of id56    zigbee_pattern = re.compile(57        "AAA_SonarCloudService_([0-9A-F][0-9A-F]:){7}[0-9A-F][0-9A-F]", flags=re.I58    )59    return zigbee_pattern.fullmatch(appliance.get("applianceId", "")) is not None60def is_alexa_guard(appliance: Dict[Text, Any]) -> bool:61    """Is the given appliance the guard alarm system of an echo."""62    return appliance["modelName"] == "REDROCK_GUARD_PANEL" and has_capability(63        appliance, "Alexa.SecurityPanelController", "armState"64    )65def is_temperature_sensor(appliance: Dict[Text, Any]) -> bool:66    """Is the given appliance the temperature sensor of an Echo."""67    return is_local(appliance) and has_capability(68        appliance, "Alexa.TemperatureSensor", "temperature"69    )70def is_light(appliance: Dict[Text, Any]) -> bool:71    """Is the given appliance a light controlled locally by an Echo."""72    return (73        is_local(appliance)74        and "LIGHT" in appliance["applianceTypes"]75        and has_capability(appliance, "Alexa.PowerController", "powerState")76    )77def get_friendliest_name(appliance: Dict[Text, Any]) -> Text:78    """Find the best friendly name. Alexa seems to store manual renames in aliases. Prefer that one."""79    aliases = appliance.get("aliases", [])80    for alias in aliases:81        friendly = alias.get("friendlyName")82        if friendly:83            return friendly84    return appliance["friendlyName"]85def get_device_serial(appliance: Dict[Text, Any]) -> Optional[Text]:86    """Find the device serial id if it is present."""87    alexa_device_id_list = appliance.get("alexaDeviceIdentifierList", [])88    for alexa_device_id in alexa_device_id_list:89        if isinstance(alexa_device_id, dict):90            return alexa_device_id.get("dmsDeviceSerialNumber")91    return None92class AlexaEntity(TypedDict):93    """Class for Alexaentity."""94    id: Text95    appliance_id: Text96    name: Text97    is_hue_v1: bool98class AlexaLightEntity(AlexaEntity):99    """Class for AlexaLightEntity."""100    brightness: bool101    color: bool102    color_temperature: bool103class AlexaTemperatureEntity(AlexaEntity):104    """Class for AlexaTemperatureEntity."""105    device_serial: Text106class AlexaEntities(TypedDict):107    """Class for holding entities."""108    light: List[AlexaLightEntity]109    guard: List[AlexaEntity]110    temperature: List[AlexaTemperatureEntity]111def parse_alexa_entities(network_details: Optional[Dict[Text, Any]]) -> AlexaEntities:112    """Turn the network details into a list of useful entities with the important details extracted."""113    lights = []114    guards = []115    temperature_sensors = []116    location_details = network_details["locationDetails"]["locationDetails"]117    for location in location_details.values():118        amazon_bridge_details = location["amazonBridgeDetails"]["amazonBridgeDetails"]119        for bridge in amazon_bridge_details.values():120            appliance_details = bridge["applianceDetails"]["applianceDetails"]121            for appliance in appliance_details.values():122                processed_appliance = {123                    "id": appliance["entityId"],124                    "appliance_id": appliance["applianceId"],125                    "name": get_friendliest_name(appliance),126                    "is_hue_v1": is_hue_v1(appliance),127                }128                if is_alexa_guard(appliance):129                    guards.append(processed_appliance)130                elif is_temperature_sensor(appliance):131                    serial = get_device_serial(appliance)132                    processed_appliance["device_serial"] = (133                        serial if serial else appliance["entityId"]134                    )135                    temperature_sensors.append(processed_appliance)136                elif is_light(appliance):137                    processed_appliance["brightness"] = has_capability(138                        appliance, "Alexa.BrightnessController", "brightness"139                    )140                    processed_appliance["color"] = has_capability(141                        appliance, "Alexa.ColorController", "color"142                    )143                    processed_appliance["color_temperature"] = has_capability(144                        appliance,145                        "Alexa.ColorTemperatureController",146                        "colorTemperatureInKelvin",147                    )148                    lights.append(processed_appliance)149    return {"light": lights, "guard": guards, "temperature": temperature_sensors}150class AlexaCapabilityState(TypedDict):151    """Class for AlexaCapabilityState."""152    name: Text153    namespace: Text154    value: Union[int, Text, TypedDict]155AlexaEntityData = Dict[Text, List[AlexaCapabilityState]]156async def get_entity_data(157    login_obj: AlexaLogin, entity_ids: List[Text]...cover.py
Source:cover.py  
...59    @property60    def supported_features(self) -> int:61        """Flag supported features."""62        supported_features = 063        if self.has_capability("open"):64            supported_features |= CoverEntityFeature.OPEN65        if self.has_capability("close"):66            supported_features |= CoverEntityFeature.CLOSE67        if self.has_capability("stop"):68            supported_features |= CoverEntityFeature.STOP69        if self.has_capability("position"):70            supported_features |= CoverEntityFeature.SET_POSITION71        if self.has_capability("rotation"):72            supported_features |= (73                CoverEntityFeature.OPEN_TILT74                | CoverEntityFeature.CLOSE_TILT75                | CoverEntityFeature.STOP_TILT76                | CoverEntityFeature.SET_TILT_POSITION77            )78        return supported_features79    async def async_close_cover(self, **kwargs):80        """Close the cover."""81        self._is_closing = True82        self.async_write_ha_state()83        try:84            # Blocks until the close command is sent85            await self.hass.async_add_executor_job(self._cover.close)...test_capabilities.py
Source:test_capabilities.py  
2from rbtools.api.capabilities import Capabilities3from rbtools.testing import TestCase4class CapabilitiesTests(TestCase):5    """Tests for rbtools.api.capabilities.Capabilities"""6    def test_has_capability(self):7        """Testing Capabilities.has_capability with supported capability"""8        caps = Capabilities({9            'foo': {10                'bar': {11                    'value': True,12                },13            },14        })15        self.assertTrue(caps.has_capability('foo', 'bar', 'value'))16    def test_has_capability_with_unknown_capability(self):17        """Testing Capabilities.has_capability with unknown capability"""18        caps = Capabilities({})19        self.assertFalse(caps.has_capability('mycap'))20    def test_has_capability_with_partial_path(self):21        """Testing Capabilities.has_capability with partial capability path"""22        caps = Capabilities({23            'foo': {24                'bar': {25                    'value': True,26                },27            },28        })...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
