Example #1
0
def test_set_name():
    dev = Device(LIGHT_WS)
    command = dev.set_name('New name')

    assert command.method == 'put'
    assert command.path == dev.path
    assert command.data == {ATTR_NAME: 'New name'}
def test_setters():
    """Test light setters."""
    cmd = Device(LIGHT_CWS).light_control.set_predefined_color("Warm glow")
    assert cmd.data == {"3311": [{"5706": "efd275"}]}

    with pytest.raises(error.ColorError):
        Device(LIGHT_CWS).light_control.set_predefined_color("Ggravlingen")
Example #3
0
def test_set_name(mock_api):
    dev = Device(mock_api, LIGHT)
    dev.set_name('New name')
    assert len(mock_api.calls) == 1
    req = mock_api.calls[0]
    assert req['method'] == 'put'
    assert req['path'] == dev.path
    assert req['data'] == {ATTR_NAME: 'New name'}
Example #4
0
def test_binary_division():
    dev_ws = Device(LIGHT_WS).light_control.lights[0]
    dev_color = Device(LIGHT_CWS).light_control.lights[0]

    assert dev_ws.dimmer == 254
    assert dev_ws.color_temp == 400
    assert dev_color.hex_color == 'f1e0b5'
    assert dev_color.xy_color == (30015, 26870)
Example #5
0
def test_setters():
    cmd = Device(LIGHT_CWS).light_control \
        .set_predefined_color('Warm glow')
    assert cmd.data == {'3311': [{'5706': 'efd275'}]}

    with pytest.raises(error.ColorError):
        Device(LIGHT_CWS).light_control \
            .set_predefined_color('Ggravlingen')
Example #6
0
def test_last_seen():
    dev = Device(LIGHT_WS)
    assert dev.last_seen is not None

    tmp = LIGHT_WS
    del tmp[ATTR_LAST_SEEN]
    dev = Device(tmp)
    assert dev.last_seen is None
Example #7
0
def test_has_light_control():
    dev = Device(LIGHT_WS)
    assert dev.has_light_control is True
    dev = Device(LIGHT_CWS)
    assert dev.has_light_control is True
    dev = Device(LIGHT_W)
    assert dev.has_light_control is True
    dev = Device(REMOTE_CONTROL)
    assert dev.has_light_control is False
    dev = Device(MOTION_SENSOR)
    assert dev.has_light_control is False
Example #8
0
def test_has_light_control_false():
    """Test light do not have control."""
    response = deepcopy(LIGHT_WS)
    response.pop(ATTR_LIGHT_CONTROL)
    dev = Device(response)

    assert dev.has_light_control is False
Example #9
0
def test_device_info_power_source_str_unknown():
    """Test power source unknown."""
    response = deepcopy(LIGHT_WS)
    response[ATTR_DEVICE_INFO]["6"] = 99999
    info = Device(response).device_info

    assert info.power_source_str == "Unknown"
Example #10
0
def test_device_info_power_source_not_present():
    """Test power source not present."""
    response = deepcopy(LIGHT_WS)
    del response[ATTR_DEVICE_INFO]["6"]
    info = Device(response).device_info

    assert info.power_source_str is None
Example #11
0
def test_device_info_battery_level_unknown(comment: str, device: Device) -> None:
    """Test battery level unknown."""
    response = deepcopy(device)
    response[ATTR_DEVICE_INFO].pop("9")
    info = Device(response).device_info

    assert info.battery_level is None
async def test_turn_on(hass,
                       mock_gateway,
                       mock_api,
                       test_features,
                       test_data,
                       expected_result,
                       id):
    """Test turning on a light."""
    # Note pytradfri style, not hass. Values not really important.
    initial_state = {
        'state': False,
        'dimmer': 0,
        'color_temp': 250,
        'hsb_xy_color': (100, 100, 100, 100, 100)
    }

    # Setup the gateway with a mock light.
    light = mock_light(test_features=test_features,
                       test_state=initial_state,
                       n=id)
    mock_gateway.mock_devices.append(light)
    await setup_gateway(hass, mock_gateway, mock_api)

    # Use the turn_on service call to change the light state.
    await hass.services.async_call('light', 'turn_on', {
        'entity_id': 'light.tradfri_light_{}'.format(id),
        **test_data
    }, blocking=True)
    await hass.async_block_till_done()

    # Check that the light is observed.
    mock_func = light.observe
    assert len(mock_func.mock_calls) > 0
    _, callkwargs = mock_func.call_args
    assert 'callback' in callkwargs
    # Callback function to refresh light state.
    cb = callkwargs['callback']

    responses = mock_gateway.mock_responses
    # State on command data.
    data = {'3311': [{'5850': 1}]}
    # Add data for all sent commands.
    for r in responses:
        data['3311'][0] = {**data['3311'][0], **r['3311'][0]}

    # Use the callback function to update the light state.
    dev = Device(data)
    light_data = Light(dev, 0)
    light.light_control.lights[0] = light_data
    cb(light)
    await hass.async_block_till_done()

    # Check that the state is correct.
    states = hass.states.get('light.tradfri_light_{}'.format(id))
    for k, v in expected_result.items():
        if k == 'state':
            assert states.state == v
        else:
            # Allow some rounding error in color conversions.
            assert states.attributes[k] == pytest.approx(v, abs=0.01)
async def test_turn_on(hass, mock_gateway, mock_api, test_features, test_data,
                       expected_result, id):
    """Test turning on a light."""
    # Note pytradfri style, not hass. Values not really important.
    initial_state = {
        "state": False,
        "dimmer": 0,
        "color_temp": 250,
        "hsb_xy_color": (100, 100, 100, 100, 100),
    }

    # Setup the gateway with a mock light.
    light = mock_light(test_features=test_features,
                       test_state=initial_state,
                       n=id)
    mock_gateway.mock_devices.append(light)
    await setup_gateway(hass, mock_gateway, mock_api)

    # Use the turn_on service call to change the light state.
    await hass.services.async_call(
        "light",
        "turn_on",
        {
            "entity_id": f"light.tradfri_light_{id}",
            **test_data
        },
        blocking=True,
    )
    await hass.async_block_till_done()

    # Check that the light is observed.
    mock_func = light.observe
    assert len(mock_func.mock_calls) > 0
    _, callkwargs = mock_func.call_args
    assert "callback" in callkwargs
    # Callback function to refresh light state.
    cb = callkwargs["callback"]

    responses = mock_gateway.mock_responses
    # State on command data.
    data = {"3311": [{"5850": 1}]}
    # Add data for all sent commands.
    for r in responses:
        data["3311"][0] = {**data["3311"][0], **r["3311"][0]}

    # Use the callback function to update the light state.
    dev = Device(data)
    light_data = Light(dev, 0)
    light.light_control.lights[0] = light_data
    cb(light)
    await hass.async_block_till_done()

    # Check that the state is correct.
    states = hass.states.get(f"light.tradfri_light_{id}")
    for k, v in expected_result.items():
        if k == "state":
            assert states.state == v
        else:
            # Allow some rounding error in color conversions.
            assert states.attributes[k] == pytest.approx(v, abs=0.01)
Example #14
0
def test_device_info_serial():
    """Test serial number."""
    response = deepcopy(LIGHT_WS)
    response[ATTR_DEVICE_INFO]["2"] = "SomeRandomSerial"
    info = Device(response).device_info

    assert info.serial == "SomeRandomSerial"
Example #15
0
def device_fixture(request: pytest.FixtureRequest) -> Device:
    """Return device."""
    if hasattr(request, "param"):
        response = deepcopy(request.param)
    else:
        response = deepcopy(LIGHT_WS)
    return Device(response)
Example #16
0
def test_socket_state_on():
    """Test socket on."""
    socket_response = deepcopy(OUTLET)
    socket_response[ATTR_SWITCH_PLUG][0][ATTR_DEVICE_STATE] = 1

    socket = Device(socket_response).socket_control.sockets[0]
    assert socket.state is True
Example #17
0
def test_light_state_off():
    """Test light off."""
    device_data = deepcopy(LIGHT_WS)
    device_data[ATTR_LIGHT_CONTROL][0][ATTR_DEVICE_STATE] = 0
    device = Device(device_data)
    light = device.light_control.lights[0]
    assert light.state is False
Example #18
0
def test_device_properties():
    dev = Device(LIGHT)

    assert dev.application_type == 2
    assert dev.name == 'Light name'
    assert dev.id == 65537
    assert dev.reachable
    assert dev.path == [ROOT_DEVICES, 65537]
Example #19
0
def test_device_info_properties():
    info = Device(LIGHT_WS).device_info

    assert info.manufacturer == 'IKEA of Sweden'
    assert info.model_number == 'TRADFRI bulb E27 WS opal 980lm'
    assert info.firmware_version == '1.2.217'
    assert info.power_source == 1
    assert info.power_source_str == 'Internal Battery'
Example #20
0
def test_light_state_mangled():
    """Test mangled light state."""
    device_data = deepcopy(LIGHT_WS)
    device_data[ATTR_LIGHT_CONTROL][0][ATTR_DEVICE_STATE] = "RandomString"
    with pytest.raises(ValueError):
        device = Device(device_data)
        light = device.light_control.lights[0]
        assert light.state is False
Example #21
0
def test_device_properties():
    dev = Device(LIGHT_WS)

    assert dev.application_type == 2
    assert dev.name == 'Löng name containing viking lättårs [letters]'
    assert dev.id == 65539
    assert dev.created_at == datetime.utcfromtimestamp(1509923713)
    assert dev.reachable
    assert dev.path == [ROOT_DEVICES, 65539]
Example #22
0
async def test_set_percentage(
    hass,
    mock_gateway,
    mock_api_factory,
    test_data,
    expected_result,
):
    """Test setting speed of a fan."""
    # Note pytradfri style, not hass. Values not really important.
    initial_state = {"percentage": 10, "fan_speed": 3, "air_quality": 12}
    # Setup the gateway with a mock fan.
    fan = mock_fan(test_state=initial_state, device_number=0)
    mock_gateway.mock_devices.append(fan)
    await setup_integration(hass)

    # Use the turn_on service call to change the fan state.
    await hass.services.async_call(
        "fan",
        "set_percentage",
        {
            "entity_id": "fan.tradfri_fan_0",
            **test_data
        },
        blocking=True,
    )
    await hass.async_block_till_done()

    # Check that the fan is observed.
    mock_func = fan.observe
    assert len(mock_func.mock_calls) > 0
    _, callkwargs = mock_func.call_args
    assert "callback" in callkwargs
    # Callback function to refresh fan state.
    callback = callkwargs["callback"]

    responses = mock_gateway.mock_responses
    mock_gateway_response = responses[0]

    # A KeyError is raised if we don't this to the response code
    mock_gateway_response["15025"][0].update({
        "5908": 10,
        "5907": 12,
        "5910": 20
    })

    # Use the callback function to update the fan state.
    dev = Device(mock_gateway_response)
    fan_data = AirPurifier(dev, 0)
    fan.air_purifier_control.air_purifiers[0] = fan_data
    callback(fan)
    await hass.async_block_till_done()

    # Check that the state is correct.
    state = hass.states.get("fan.tradfri_fan_0")
    assert state.state == expected_result
def test_combine_command():
    """Test light control combine command."""
    device = Device(LIGHT_CWS)

    assert device.light_control is not None

    dimmer_cmd = device.light_control.set_dimmer(100)

    assert dimmer_cmd.data == {"3311": [{"5851": 100}]}

    hsb_xy_color_cmd = device.light_control.set_hsb(hue=100,
                                                    saturation=75,
                                                    brightness=50,
                                                    transition_time=60)

    assert hsb_xy_color_cmd.data == {
        "3311": [{
            "5707": 100,
            "5708": 75,
            "5712": 60,
            "5851": 50
        }]
    }

    combined_cmd = device.light_control.combine_commands(
        [dimmer_cmd, hsb_xy_color_cmd])

    assert combined_cmd.data == {
        "3311": [{
            "5707": 100,
            "5708": 75,
            "5712": 60,
            "5851": 50
        }]
    }

    combined_cmd = device.light_control.combine_commands(
        [combined_cmd, dimmer_cmd])

    assert combined_cmd.data == {
        "3311": [{
            "5707": 100,
            "5708": 75,
            "5712": 60,
            "5851": 100
        }]
    }

    combined_cmd.data.clear()

    with pytest.raises(TypeError):
        device.light_control.combine_commands([dimmer_cmd, combined_cmd])
Example #24
0
def test_set_state():
    dev = Device(LIGHT_WS)

    with pytest.raises(TypeError):
        dev.light_control.set_state(None)

    command = dev.light_control.set_state(True)
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 1

    command = dev.light_control.set_state(False)
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 1
Example #25
0
async def test_set_cover_position(
    hass,
    mock_gateway,
    mock_api_factory,
    test_data,
    expected_result,
):
    """Test setting position of a cover."""
    # Note pytradfri style, not hass. Values not really important.
    initial_state = {
        "current_cover_position": 0,
    }

    # Setup the gateway with a mock cover.
    cover = mock_cover(test_state=initial_state, device_number=0)
    mock_gateway.mock_devices.append(cover)
    await setup_integration(hass)

    # Use the turn_on service call to change the cover state.
    await hass.services.async_call(
        "cover",
        "set_cover_position",
        {
            "entity_id": "cover.tradfri_cover_0",
            **test_data
        },
        blocking=True,
    )
    await hass.async_block_till_done()

    # Check that the cover is observed.
    mock_func = cover.observe
    assert len(mock_func.mock_calls) > 0
    _, callkwargs = mock_func.call_args
    assert "callback" in callkwargs
    # Callback function to refresh cover state.
    callback = callkwargs["callback"]

    responses = mock_gateway.mock_responses

    # Use the callback function to update the cover state.
    dev = Device(responses[0])
    cover_data = Blind(dev, 0)
    cover.blind_control.blinds[0] = cover_data
    callback(cover)
    await hass.async_block_till_done()

    # Check that the state is correct.
    state = hass.states.get("cover.tradfri_cover_0")
    assert state.state == expected_result
Example #26
0
async def test_turn_on_off(
    hass,
    mock_gateway,
    mock_api_factory,
    test_data,
    expected_result,
):
    """Test turning switch on/off."""
    # Note pytradfri style, not hass. Values not really important.
    initial_state = {
        "state": True,
    }

    # Setup the gateway with a mock switch.
    switch = mock_switch(test_state=initial_state, device_number=0)
    mock_gateway.mock_devices.append(switch)
    await setup_integration(hass)

    # Use the turn_on/turn_off service call to change the switch state.
    await hass.services.async_call(
        "switch",
        test_data,
        {
            "entity_id": "switch.tradfri_switch_0",
        },
        blocking=True,
    )
    await hass.async_block_till_done()

    # Check that the switch is observed.
    mock_func = switch.observe
    assert len(mock_func.mock_calls) > 0
    _, callkwargs = mock_func.call_args
    assert "callback" in callkwargs
    # Callback function to refresh switch state.
    callback = callkwargs["callback"]

    responses = mock_gateway.mock_responses
    mock_gateway_response = responses[0]

    # Use the callback function to update the switch state.
    dev = Device(mock_gateway_response)
    switch_data = Socket(dev, 0)
    switch.socket_control.sockets[0] = switch_data
    callback(switch)
    await hass.async_block_till_done()

    # Check that the state is correct.
    state = hass.states.get("switch.tradfri_switch_0")
    assert state.state == expected_result
Example #27
0
def test_set_hex_color():
    dev = Device(LIGHT_WS)

    command = dev.light_control.set_hex_color("4a418a")
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 1

    command = dev.light_control.set_hex_color("4a418a", transition_time=1)
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 2

    command = dev.light_control.set_hex_color("RandomString")
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 1
Example #28
0
def test_set_color_temp():
    dev = Device(LIGHT_WS)

    command = dev.light_control.set_color_temp(300)
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 1

    command = dev.light_control.set_color_temp(None)
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 1

    command = dev.light_control.set_color_temp(300, transition_time=1)
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 2
Example #29
0
def test_value_validate():
    dev = Device(LIGHT_WS)
    rnge = (10, 100)

    with pytest.raises(ValueError):
        dev.light_control._value_validate(9, rnge)
    with pytest.raises(ValueError):
        dev.light_control._value_validate(-1, rnge)
    with pytest.raises(ValueError):
        dev.light_control._value_validate(101, rnge)

    assert dev.light_control._value_validate(10, rnge) is None
    assert dev.light_control._value_validate(50, rnge) is None
    assert dev.light_control._value_validate(100, rnge) is None
    assert dev.light_control._value_validate(None, rnge) is None
Example #30
0
def test_set_hsb():
    dev = Device(LIGHT_WS)

    command = dev.light_control.set_hsb(300, 200)
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 2

    command = dev.light_control.set_hsb(300, 200, None)
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 2

    command = dev.light_control.set_hsb(300, 200, 100)
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 3

    command = dev.light_control.set_hsb(300, 200, 100, transition_time=1)
    data = command.data[ATTR_LIGHT_CONTROL][0]
    assert len(data) is 4