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

    assert command.method == 'put'
    assert command.path == dev.path
    assert command.data == {ATTR_NAME: 'New name'}
Example #2
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 #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_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 #5
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 #6
0
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)
Example #7
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 #8
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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
Example #17
0
async def test_turn_off(hass, mock_gateway, mock_api):
    """Test turning off a light."""
    state = {
        'state': True,
        'dimmer': 100,
    }

    light = mock_light(test_state=state)
    mock_gateway.mock_devices.append(light)
    await setup_gateway(hass, mock_gateway, mock_api)

    # Use the turn_off service call to change the light state.
    await hass.services.async_call('light',
                                   'turn_off',
                                   {'entity_id': 'light.tradfri_light_0'},
                                   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
    data = {'3311': [{}]}
    # 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_0')
    assert states.state == 'off'
Example #18
0
async def test_turn_off(hass, mock_gateway, mock_api_factory):
    """Test turning off a light."""
    state = {"state": True, "dimmer": 100}

    light = mock_light(test_state=state)
    mock_gateway.mock_devices.append(light)
    await setup_integration(hass)

    # Use the turn_off service call to change the light state.
    await hass.services.async_call("light",
                                   "turn_off",
                                   {"entity_id": "light.tradfri_light_0"},
                                   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.
    callback = callkwargs["callback"]

    responses = mock_gateway.mock_responses
    data = {"3311": [{}]}
    # Add data for all sent commands.
    for resp in responses:
        data["3311"][0] = {**data["3311"][0], **resp["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
    callback(light)
    await hass.async_block_till_done()

    # Check that the state is correct.
    states = hass.states.get("light.tradfri_light_0")
    assert states.state == "off"
Example #19
0
def test_has_light_control_true():
    """Test light has control."""
    response = deepcopy(LIGHT_WS)
    dev = Device(response)

    assert dev.has_light_control is True
Example #20
0
def test_socket_value_setting(function_name, comment, test_input, expected_result):
    """Test socket values."""
    function = getattr(Device(deepcopy(OUTLET)).socket_control, function_name)
    command = function(**test_input)
    data = command.data[ATTR_SWITCH_PLUG][0]
    assert data == expected_result
Example #21
0
        response = deepcopy(LIGHT_WS)
    return Device(response)


input_devices = (
    ("comment", "device"),
    [
        ("Remote control", REMOTE_CONTROL),
        ("Motion sensor", MOTION_SENSOR),
    ],
)

output_devices = (
    ("comment", "device"),
    [
        ("White fixed color bulb", Device(LIGHT_W)),
        ("White spectrum bulb", Device(LIGHT_WS)),
        ("Full color bulb", Device(LIGHT_CWS)),
        ("Philips Hue bulb", Device(LIGHT_PHILIPS)),
    ],
)

wall_plugs = (("comment", "device"), [("Wall plug", Device(OUTLET))])

roller_blinds = (("comment", "device"), [("Blind", Device(BLIND))])

lamp_value_setting_test_cases = [
    ["function_name", "comment", "test_input", "expected_result"],
    [
        [
            "set_hsb",
Example #22
0
async def test_turn_on(
    hass,
    mock_gateway,
    mock_api_factory,
    test_features,
    test_data,
    expected_result,
    device_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,
                       light_number=device_id)
    mock_gateway.mock_devices.append(light)
    await setup_integration(hass)

    # 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_{device_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.
    callback = callkwargs["callback"]

    responses = mock_gateway.mock_responses
    # State on command data.
    data = {"3311": [{"5850": 1}]}
    # Add data for all sent commands.
    for resp in responses:
        data["3311"][0] = {**data["3311"][0], **resp["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
    callback(light)
    await hass.async_block_till_done()

    # Check that the state is correct.
    states = hass.states.get(f"light.tradfri_light_{device_id}")
    for result, value in expected_result.items():
        if result == "state":
            assert states.state == value
        else:
            # Allow some rounding error in color conversions.
            assert states.attributes[result] == pytest.approx(value, abs=0.01)
Example #23
0
def test_deviceinfo_battery_level_unkown(comment, device):
    info = Device(device.raw.copy()).device_info
    info.raw['9'] = None
    assert info.battery_level is None
Example #24
0
def test_last_seen_none():
    """Test last seen none."""
    response = deepcopy(LIGHT_WS)
    del response[ATTR_LAST_SEEN]
    dev = Device(response)
    assert dev.last_seen is None
Example #25
0
def test_light_hsb_xy_color():
    """Very basic test, just to touch it."""
    device_data = deepcopy(LIGHT_CWS)
    device = Device(device_data)
    light = device.light_control.lights[0]
    assert len(light.hsb_xy_color) == 5
Example #26
0
def test_deviceinfo_power_source_str_unknown(device):
    info = Device(device.raw.copy()).device_info
    info.raw['6'] = None
    assert info.power_source_str == 'Unknown'
Example #27
0
def test_device_info_power_source_str_known():
    """Test power source known."""
    info = Device(deepcopy(LIGHT_WS)).device_info
    assert info.power_source_str is not None
    assert info.power_source_str != "Unknown"
Example #28
0
def test_deviceinfo_power_source_not_present(device):
    info = Device(device.raw.copy()).device_info
    del info.raw['6']
    assert info.power_source_str is None
Example #29
0
def device():
    return Device(BLIND)
Example #30
0
def test_deviceinfo_battery_level(comment, device):
    info = Device(device.raw.copy()).device_info
    assert type(info.battery_level) is int
    assert info.battery_level >= 0
    assert info.battery_level <= 100