コード例 #1
0
def test_get_device_config(hass, test_client):
    """Test getting device config."""
    app = mock_http_component_app(hass)

    with patch.object(config, 'SECTIONS', ['group']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[VIEW_NAME].register(app.router)

    client = yield from test_client(app)

    def mock_read(path):
        """Mock reading data."""
        return {
            'hello.beer': {
                'free': 'beer',
            },
            'other.entity': {
                'do': 'something',
            },
        }

    with patch('homeassistant.components.config._read', mock_read):
        resp = yield from client.get(
            '/api/config/group/config/hello.beer')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {'free': 'beer'}
コード例 #2
0
ファイル: test_api.py プロジェクト: tedstriker/home-assistant
def test_get_config(hass, test_client):
    """Test getting config on node."""
    app = mock_http_component_app(hass)
    ZWaveNodeConfigView().register(app.router)

    network = hass.data[DATA_NETWORK] = MagicMock()
    node = MockNode(node_id=2)
    value = MockValue(
        index=12,
        command_class=const.COMMAND_CLASS_CONFIGURATION)
    value.label = 'label'
    value.help = 'help'
    value.type = 'type'
    value.data = 'data'
    value.data_items = ['item1', 'item2']
    value.max = 'max'
    value.min = 'min'
    node.values = {12: value}
    network.nodes = {2: node}
    node.get_values.return_value = node.values

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/config/2')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {'12': {'data': 'data',
                             'data_items': ['item1', 'item2'],
                             'help': 'help',
                             'label': 'label',
                             'max': 'max',
                             'min': 'min',
                             'type': 'type'}}
コード例 #3
0
ファイル: test_html5.py プロジェクト: devanl/home-assistant
    def test_registering_new_device_expiration_view(self, loop, test_client):
        """Test that the HTML view works."""
        hass = MagicMock()
        expected = {
            'unnamed device': SUBSCRIPTION_4,
        }

        hass.config.path.return_value = CONFIG_FILE
        service = html5.get_service(hass, {})

        assert service is not None

        # assert hass.called
        assert len(hass.mock_calls) == 3

        view = hass.mock_calls[1][1][0]
        assert view.json_path == hass.config.path.return_value
        assert view.registrations == {}

        hass.loop = loop
        app = mock_http_component_app(hass)
        view.register(app.router)
        client = yield from test_client(app)
        hass.http.is_banned_ip.return_value = False
        resp = yield from client.post(REGISTER_URL,
                                      data=json.dumps(SUBSCRIPTION_4))

        content = yield from resp.text()
        assert resp.status == 200, content
        assert view.registrations == expected

        hass.async_add_job.assert_called_with(save_json, CONFIG_FILE, expected)
コード例 #4
0
ファイル: test_api.py プロジェクト: tedstriker/home-assistant
def test_get_usercodes_no_genreuser(hass, test_client):
    """Test getting usercodes on node missing genre user."""
    app = mock_http_component_app(hass)
    ZWaveUserCodeView().register(app.router)

    network = hass.data[DATA_NETWORK] = MagicMock()
    node = MockNode(node_id=18,
                    command_classes=[const.COMMAND_CLASS_USER_CODE])
    value = MockValue(
        index=0,
        command_class=const.COMMAND_CLASS_USER_CODE)
    value.genre = const.GENRE_SYSTEM
    value.label = 'label'
    value.data = '1234'
    node.values = {0: value}
    network.nodes = {18: node}
    node.get_values.return_value = node.values

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/usercodes/18')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {}
コード例 #5
0
ファイル: test_api.py プロジェクト: tedstriker/home-assistant
def test_get_groups(hass, test_client):
    """Test getting groupdata on node."""
    app = mock_http_component_app(hass)
    ZWaveNodeGroupView().register(app.router)

    network = hass.data[DATA_NETWORK] = MagicMock()
    node = MockNode(node_id=2)
    node.groups.associations = 'assoc'
    node.groups.associations_instances = 'inst'
    node.groups.label = 'the label'
    node.groups.max_associations = 'max'
    node.groups = {1: node.groups}
    network.nodes = {2: node}

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/groups/2')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {
        '1': {
            'association_instances': 'inst',
            'associations': 'assoc',
            'label': 'the label',
            'max_associations': 'max'
        }
    }
コード例 #6
0
ファイル: test_api.py プロジェクト: tedstriker/home-assistant
def test_get_values(hass, test_client):
    """Test getting values on node."""
    app = mock_http_component_app(hass)
    ZWaveNodeValueView().register(app.router)

    node = MockNode(node_id=1)
    value = MockValue(value_id=123456, node=node, label='Test Label')
    values = MockEntityValues(primary=value)
    node2 = MockNode(node_id=2)
    value2 = MockValue(value_id=234567, node=node2, label='Test Label 2')
    values2 = MockEntityValues(primary=value2)
    hass.data[const.DATA_ENTITY_VALUES] = [values, values2]

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/values/1')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {
        '123456': {
            'label': 'Test Label',
        }
    }
コード例 #7
0
    def test_callback_view_no_jwt(self, loop, test_client):
        """Test that the notification callback view works without JWT."""
        hass = MagicMock()

        m = mock_open()
        with patch(
            'homeassistant.util.json.open',
            m, create=True
        ):
            hass.config.path.return_value = 'file.conf'
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[2][1][0]

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            resp = yield from client.post(PUBLISH_URL, data=json.dumps({
                'type': 'push',
                'tag': '3bc28d69-0921-41f1-ac6a-7a627ba0aa72'
            }))

            assert resp.status == 401, resp.response
コード例 #8
0
    def test_registering_new_device_view(self, loop, test_client):
        """Test that the HTML view works."""
        hass = MagicMock()
        expected = {"unnamed device": SUBSCRIPTION_1}

        m = mock_open()
        with patch("homeassistant.components.notify.html5.open", m, create=True):
            hass.config.path.return_value = "file.conf"
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]
            assert view.json_path == hass.config.path.return_value
            assert view.registrations == {}

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False
            resp = yield from client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))

            content = yield from resp.text()
            assert resp.status == 200, content
            assert view.registrations == expected
            handle = m()
            assert json.loads(handle.write.call_args[0][0]) == expected
コード例 #9
0
    def test_unregister_device_view_handle_unknown_subscription(self, loop, test_client):
        """Test that the HTML unregister view handles unknown subscriptions."""
        hass = MagicMock()

        config = {"some device": SUBSCRIPTION_1, "other device": SUBSCRIPTION_2}

        m = mock_open(read_data=json.dumps(config))
        with patch("homeassistant.components.notify.html5.open", m, create=True):
            hass.config.path.return_value = "file.conf"
            with patch("homeassistant.components.notify.html5.os.path.isfile", return_value=True):
                service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]
            assert view.json_path == hass.config.path.return_value
            assert view.registrations == config

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            resp = yield from client.delete(
                REGISTER_URL, data=json.dumps({"subscription": SUBSCRIPTION_3["subscription"]})
            )

            assert resp.status == 200, resp.response
            assert view.registrations == config
            handle = m()
            assert handle.write.call_count == 0
コード例 #10
0
ファイル: test_html5.py プロジェクト: devanl/home-assistant
    def test_registering_existing_device_fails_view(self, loop, test_client):
        """Test sub. is not updated when registering existing device fails."""
        hass = MagicMock()
        expected = {
            'unnamed device': SUBSCRIPTION_1,
        }

        hass.config.path.return_value = CONFIG_FILE
        html5.get_service(hass, {})
        view = hass.mock_calls[1][1][0]

        hass.loop = loop
        app = mock_http_component_app(hass)
        view.register(app.router)
        client = yield from test_client(app)
        hass.http.is_banned_ip.return_value = False

        yield from client.post(REGISTER_URL,
                               data=json.dumps(SUBSCRIPTION_1))

        hass.async_add_job.side_effect = HomeAssistantError()
        resp = yield from client.post(REGISTER_URL,
                                      data=json.dumps(SUBSCRIPTION_4))

        content = yield from resp.text()
        assert resp.status == 500, content
        assert view.registrations == expected
コード例 #11
0
def test_validate_config_ok(hass, test_client):
    """Test checking config."""
    app = mock_http_component_app(hass)
    with patch.object(config, 'SECTIONS', ['core']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[CheckConfigView.name].register(app.router)
    client = yield from test_client(app)

    with patch(
        'homeassistant.components.config.core.async_check_ha_config_file',
            return_value=mock_coro()):
        resp = yield from client.post('/api/config/core/check_config')

    assert resp.status == 200
    result = yield from resp.json()
    assert result['result'] == 'valid'
    assert result['errors'] is None

    with patch(
        'homeassistant.components.config.core.async_check_ha_config_file',
            return_value=mock_coro('beer')):
        resp = yield from client.post('/api/config/core/check_config')

    assert resp.status == 200
    result = yield from resp.json()
    assert result['result'] == 'invalid'
    assert result['errors'] == 'beer'
コード例 #12
0
ファイル: test_html5.py プロジェクト: Khabi/home-assistant
    def test_callback_view_with_jwt(self, loop, test_client):
        """Test that the notification callback view works with JWT."""
        hass = MagicMock()

        data = {
            'device': SUBSCRIPTION_1,
        }

        m = mock_open(read_data=json.dumps(data))
        with patch(
                'homeassistant.components.notify.html5.open', m, create=True
        ):
            hass.config.path.return_value = 'file.conf'
            with patch('homeassistant.components.notify.html5.os.path.isfile',
                       return_value=True):
                service = html5.get_service(hass, {'gcm_sender_id': '100'})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            with patch('pywebpush.WebPusher') as mock_wp:
                service.send_message('Hello', target=['device'],
                                     data={'icon': 'beer.png'})

            assert len(mock_wp.mock_calls) == 3

            # WebPusher constructor
            assert mock_wp.mock_calls[0][1][0] == \
                SUBSCRIPTION_1['subscription']
            # Third mock_call checks the status_code of the response.
            assert mock_wp.mock_calls[2][0] == '().send().status_code.__eq__'

            # Call to send
            push_payload = json.loads(mock_wp.mock_calls[1][1][0])

            assert push_payload['body'] == 'Hello'
            assert push_payload['icon'] == 'beer.png'

            view = hass.mock_calls[2][1][0]
            view.registrations = data

            bearer_token = "Bearer {}".format(push_payload['data']['jwt'])

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            resp = yield from client.post(PUBLISH_URL, data=json.dumps({
                'type': 'push',
            }), headers={'Authorization': bearer_token})

            assert resp.status == 200
            body = yield from resp.json()
            assert body == {"event": "push", "status": "ok"}
コード例 #13
0
def hue_client(loop, hass_hue, test_client):
    """Create web client for emulated hue api."""
    web_app = mock_http_component_app(hass_hue)
    config = Config(None, {'type': 'alexa'})

    HueUsernameView().register(web_app.router)
    HueAllLightsStateView(config).register(web_app.router)
    HueOneLightStateView(config).register(web_app.router)
    HueOneLightChangeView(config).register(web_app.router)

    return loop.run_until_complete(test_client(web_app))
コード例 #14
0
    def test_callback_view_with_jwt(self, loop, test_client):
        """Test that the notification callback view works with JWT."""
        hass = MagicMock()

        data = {"device": SUBSCRIPTION_1}

        m = mock_open(read_data=json.dumps(data))
        with patch("homeassistant.components.notify.html5.open", m, create=True):
            hass.config.path.return_value = "file.conf"
            with patch("homeassistant.components.notify.html5.os.path.isfile", return_value=True):
                service = html5.get_service(hass, {"gcm_sender_id": "100"})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            with patch("pywebpush.WebPusher") as mock_wp:
                service.send_message("Hello", target=["device"], data={"icon": "beer.png"})

            assert len(mock_wp.mock_calls) == 2

            # WebPusher constructor
            assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1["subscription"]

            # Call to send
            push_payload = json.loads(mock_wp.mock_calls[1][1][0])

            assert push_payload["body"] == "Hello"
            assert push_payload["icon"] == "beer.png"

            view = hass.mock_calls[2][1][0]
            view.registrations = data

            bearer_token = "Bearer {}".format(push_payload["data"]["jwt"])

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            resp = yield from client.post(
                PUBLISH_URL, data=json.dumps({"type": "push"}), headers={"Authorization": bearer_token}
            )

            assert resp.status == 200
            body = yield from resp.json()
            assert body == {"event": "push", "status": "ok"}
コード例 #15
0
def websocket_client(loop, hass, test_client):
    """Websocket client fixture connected to websocket server."""
    websocket_app = mock_http_component_app(hass)
    wapi.WebsocketAPIView().register(websocket_app.router)

    client = loop.run_until_complete(test_client(websocket_app))
    ws = loop.run_until_complete(client.ws_connect(wapi.URL))

    auth_ok = loop.run_until_complete(ws.receive_json())
    assert auth_ok['type'] == wapi.TYPE_AUTH_OK

    yield ws

    if not ws.closed:
        loop.run_until_complete(ws.close())
コード例 #16
0
def no_auth_websocket_client(hass, loop, test_client):
    """Websocket connection that requires authentication."""
    websocket_app = mock_http_component_app(hass, API_PASSWORD)
    wapi.WebsocketAPIView().register(websocket_app.router)

    client = loop.run_until_complete(test_client(websocket_app))
    ws = loop.run_until_complete(client.ws_connect(wapi.URL))

    auth_ok = loop.run_until_complete(ws.receive_json())
    assert auth_ok['type'] == wapi.TYPE_AUTH_REQUIRED

    yield ws

    if not ws.closed:
        loop.run_until_complete(ws.close())
コード例 #17
0
def test_update_device_config_invalid_json(hass, test_client):
    """Test updating device config."""
    app = mock_http_component_app(hass)

    with patch.object(config, 'SECTIONS', ['group']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[VIEW_NAME].register(app.router)

    client = yield from test_client(app)

    resp = yield from client.post(
        '/api/config/group/config/hello_beer', data='not json')

    assert resp.status == 400
コード例 #18
0
ファイル: test_group.py プロジェクト: zircop/home-assistant
def test_update_device_config_invalid_json(hass, test_client):
    """Test updating device config."""
    app = mock_http_component_app(hass)

    with patch.object(config, 'SECTIONS', ['group']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[VIEW_NAME].register(app.router)

    client = yield from test_client(app)

    resp = yield from client.post('/api/config/group/config/hello_beer',
                                  data='not json')

    assert resp.status == 400
コード例 #19
0
ファイル: test_group.py プロジェクト: zircop/home-assistant
def test_update_device_config(hass, test_client):
    """Test updating device config."""
    app = mock_http_component_app(hass)

    with patch.object(config, 'SECTIONS', ['group']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[VIEW_NAME].register(app.router)

    client = yield from test_client(app)

    orig_data = {
        'hello.beer': {
            'ignored': True,
        },
        'other.entity': {
            'polling_intensity': 2,
        },
    }

    def mock_read(path):
        """Mock reading data."""
        return orig_data

    written = []

    def mock_write(path, data):
        """Mock writing data."""
        written.append(data)

    with patch('homeassistant.components.config._read', mock_read), \
            patch('homeassistant.components.config._write', mock_write):
        resp = yield from client.post('/api/config/group/config/hello_beer',
                                      data=json.dumps({
                                          'name':
                                          'Beer',
                                          'entities':
                                          ['light.top', 'light.bottom'],
                                      }))

    assert resp.status == 200
    result = yield from resp.json()
    assert result == {'result': 'ok'}

    orig_data['hello_beer']['name'] = 'Beer'
    orig_data['hello_beer']['entities'] = ['light.top', 'light.bottom']

    assert written[0] == orig_data
コード例 #20
0
def test_get_groups_nonode(hass, test_client):
    """Test getting groupdata on nonexisting node."""
    app = mock_http_component_app(hass)
    ZWaveNodeGroupView().register(app.router)

    network = hass.data[ZWAVE_NETWORK] = MagicMock()
    network.nodes = {1: 1, 5: 5}

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/groups/2')

    assert resp.status == 404
    result = yield from resp.json()

    assert result == {'message': 'Node not found'}
コード例 #21
0
ファイル: test_api.py プロジェクト: tedstriker/home-assistant
def test_get_groups_nonode(hass, test_client):
    """Test getting groupdata on nonexisting node."""
    app = mock_http_component_app(hass)
    ZWaveNodeGroupView().register(app.router)

    network = hass.data[DATA_NETWORK] = MagicMock()
    network.nodes = {1: 1, 5: 5}

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/groups/2')

    assert resp.status == 404
    result = yield from resp.json()

    assert result == {'message': 'Node not found'}
コード例 #22
0
    def test_unregistering_device_view_handles_json_safe_error(
            self, loop, test_client):
        """Test that the HTML unregister view handles JSON write errors."""
        hass = MagicMock()

        config = {
            'some device': SUBSCRIPTION_1,
            'other device': SUBSCRIPTION_2,
        }

        m = mock_open(read_data=json.dumps(config))
        with patch('homeassistant.components.notify.html5.open',
                   m,
                   create=True):
            hass.config.path.return_value = 'file.conf'
            with patch('homeassistant.components.notify.html5.os.path.isfile',
                       return_value=True):
                service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]
            assert view.json_path == hass.config.path.return_value
            assert view.registrations == config

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            with patch('homeassistant.components.notify.html5._save_config',
                       return_value=False):
                resp = yield from client.delete(
                    REGISTER_URL,
                    data=json.dumps({
                        'subscription':
                        SUBSCRIPTION_1['subscription'],
                    }))

            assert resp.status == 500, resp.response
            assert view.registrations == config
            handle = m()
            assert handle.write.call_count == 0
コード例 #23
0
ファイル: test_group.py プロジェクト: azogue/home-assistant
def test_update_device_config(hass, test_client):
    """Test updating device config."""
    app = mock_http_component_app(hass)

    with patch.object(config, 'SECTIONS', ['group']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[VIEW_NAME].register(app.router)

    client = yield from test_client(app)

    orig_data = {
        'hello.beer': {
            'ignored': True,
        },
        'other.entity': {
            'polling_intensity': 2,
        },
    }

    def mock_read(path):
        """Mock reading data."""
        return orig_data

    written = []

    def mock_write(path, data):
        """Mock writing data."""
        written.append(data)

    with patch('homeassistant.components.config._read', mock_read), \
            patch('homeassistant.components.config._write', mock_write):
        resp = yield from client.post(
            '/api/config/group/config/hello_beer', data=json.dumps({
                'name': 'Beer',
                'entities': ['light.top', 'light.bottom'],
            }))

    assert resp.status == 200
    result = yield from resp.json()
    assert result == {'result': 'ok'}

    orig_data['hello_beer']['name'] = 'Beer'
    orig_data['hello_beer']['entities'] = ['light.top', 'light.bottom']

    assert written[0] == orig_data
コード例 #24
0
ファイル: test_zwave.py プロジェクト: zircop/home-assistant
def test_update_device_config_invalid_key(hass, test_client):
    """Test updating device config."""
    app = mock_http_component_app(hass)

    with patch.object(config, 'SECTIONS', ['zwave']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[VIEW_NAME].register(app.router)

    client = yield from test_client(app)

    resp = yield from client.post(
        '/api/config/zwave/device_config/invalid_entity', data=json.dumps({
            'polling_intensity': 2
        }))

    assert resp.status == 400
コード例 #25
0
def test_install_suite(hass, test_client):
    """Test getting suites."""
    app = mock_http_component_app(hass)

    with patch.dict(os.environ, {'FORCE_HASSBIAN': '1'}), \
            patch.object(config, 'SECTIONS', ['hassbian']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[HassbianSuiteInstallView.name].register(app.router)

    client = yield from test_client(app)
    resp = yield from client.post(
        '/api/config/hassbian/suites/openzwave/install')
    assert resp.status == 200
    result = yield from resp.json()

    assert result == {"status": "ok"}
コード例 #26
0
def test_install_suite(hass, test_client):
    """Test getting suites."""
    app = mock_http_component_app(hass)

    with patch.dict(os.environ, {'FORCE_HASSBIAN': '1'}), \
            patch.object(config, 'SECTIONS', ['hassbian']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[HassbianSuiteInstallView.name].register(app.router)

    client = yield from test_client(app)
    resp = yield from client.post(
        '/api/config/hassbian/suites/openzwave/install')
    assert resp.status == 200
    result = yield from resp.json()

    assert result == {"status": "ok"}
コード例 #27
0
    def test_registering_new_device_validation(self, loop, test_client):
        """Test various errors when registering a new device."""
        hass = MagicMock()

        m = mock_open()
        with patch(
            'homeassistant.util.json.open',
            m, create=True
        ):
            hass.config.path.return_value = 'file.conf'
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            resp = yield from client.post(REGISTER_URL, data=json.dumps({
                'browser': 'invalid browser',
                'subscription': 'sub info',
            }))
            assert resp.status == 400

            resp = yield from client.post(REGISTER_URL, data=json.dumps({
                'browser': 'chrome',
            }))
            assert resp.status == 400

            with patch('homeassistant.components.notify.html5.save_json',
                       return_value=False):
                # resp = view.post(Request(builder.get_environ()))
                resp = yield from client.post(REGISTER_URL, data=json.dumps({
                    'browser': 'chrome',
                    'subscription': 'sub info',
                }))

            assert resp.status == 400
コード例 #28
0
ファイル: test_api.py プロジェクト: tedstriker/home-assistant
def test_get_groups_nogroups(hass, test_client):
    """Test getting groupdata on node with no groups."""
    app = mock_http_component_app(hass)
    ZWaveNodeGroupView().register(app.router)

    network = hass.data[DATA_NETWORK] = MagicMock()
    node = MockNode(node_id=2)

    network.nodes = {2: node}

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/groups/2')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {}
コード例 #29
0
def test_get_groups_nogroups(hass, test_client):
    """Test getting groupdata on node with no groups."""
    app = mock_http_component_app(hass)
    ZWaveNodeGroupView().register(app.router)

    network = hass.data[ZWAVE_NETWORK] = MagicMock()
    node = MockNode(node_id=2)

    network.nodes = {2: node}

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/groups/2')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {}
コード例 #30
0
ファイル: test_html5.py プロジェクト: zircop/home-assistant
    def test_registering_new_device_validation(self, loop, test_client):
        """Test various errors when registering a new device."""
        hass = MagicMock()

        m = mock_open()
        with patch(
                'homeassistant.components.notify.html5.open', m, create=True
        ):
            hass.config.path.return_value = 'file.conf'
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            resp = yield from client.post(REGISTER_URL, data=json.dumps({
                'browser': 'invalid browser',
                'subscription': 'sub info',
            }))
            assert resp.status == 400

            resp = yield from client.post(REGISTER_URL, data=json.dumps({
                'browser': 'chrome',
            }))
            assert resp.status == 400

            with patch('homeassistant.components.notify.html5._save_config',
                       return_value=False):
                # resp = view.post(Request(builder.get_environ()))
                resp = yield from client.post(REGISTER_URL, data=json.dumps({
                    'browser': 'chrome',
                    'subscription': 'sub info',
                }))

            assert resp.status == 400
コード例 #31
0
ファイル: test_html5.py プロジェクト: Khabi/home-assistant
    def test_unregistering_device_view_handles_json_safe_error(self, loop,
                                                               test_client):
        """Test that the HTML unregister view handles JSON write errors."""
        hass = MagicMock()

        config = {
            'some device': SUBSCRIPTION_1,
            'other device': SUBSCRIPTION_2,
        }

        m = mock_open(read_data=json.dumps(config))
        with patch(
                'homeassistant.components.notify.html5.open', m, create=True
        ):
            hass.config.path.return_value = 'file.conf'
            with patch('homeassistant.components.notify.html5.os.path.isfile',
                       return_value=True):
                service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]
            assert view.json_path == hass.config.path.return_value
            assert view.registrations == config

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            with patch('homeassistant.components.notify.html5._save_config',
                       return_value=False):
                resp = yield from client.delete(REGISTER_URL, data=json.dumps({
                    'subscription': SUBSCRIPTION_1['subscription'],
                }))

            assert resp.status == 500, resp.response
            assert view.registrations == config
            handle = m()
            assert handle.write.call_count == 0
コード例 #32
0
ファイル: test_html5.py プロジェクト: devanl/home-assistant
    def test_unregistering_device_view(self, loop, test_client):
        """Test that the HTML unregister view works."""
        hass = MagicMock()

        config = {
            'some device': SUBSCRIPTION_1,
            'other device': SUBSCRIPTION_2,
        }

        m = mock_open(read_data=json.dumps(config))
        with patch(
            'homeassistant.util.json.open',
            m, create=True
        ):
            hass.config.path.return_value = CONFIG_FILE
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]
            assert view.json_path == hass.config.path.return_value
            assert view.registrations == config

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            resp = yield from client.delete(REGISTER_URL, data=json.dumps({
                'subscription': SUBSCRIPTION_1['subscription'],
            }))

            config.pop('some device')

            assert resp.status == 200, resp.response
            assert view.registrations == config

            hass.async_add_job.assert_called_with(save_json, CONFIG_FILE,
                                                  config)
コード例 #33
0
ファイル: test_api.py プロジェクト: tedstriker/home-assistant
def test_get_usercode_nousercode_node(hass, test_client):
    """Test getting usercodes on node without usercodes."""
    app = mock_http_component_app(hass)
    ZWaveUserCodeView().register(app.router)

    network = hass.data[DATA_NETWORK] = MagicMock()
    node = MockNode(node_id=18)

    network.nodes = {18: node}
    node.get_values.return_value = node.values

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/usercodes/18')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {}
コード例 #34
0
ファイル: test_api.py プロジェクト: tedstriker/home-assistant
def test_get_config_noconfig_node(hass, test_client):
    """Test getting config on node without config."""
    app = mock_http_component_app(hass)
    ZWaveNodeConfigView().register(app.router)

    network = hass.data[DATA_NETWORK] = MagicMock()
    node = MockNode(node_id=2)

    network.nodes = {2: node}
    node.get_values.return_value = node.values

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/config/2')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {}
コード例 #35
0
def test_get_config_noconfig_node(hass, test_client):
    """Test getting config on node without config."""
    app = mock_http_component_app(hass)
    ZWaveNodeConfigView().register(app.router)

    network = hass.data[ZWAVE_NETWORK] = MagicMock()
    node = MockNode(node_id=2)

    network.nodes = {2: node}
    node.get_values.return_value = node.values

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/config/2')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {}
コード例 #36
0
def test_get_usercode_nousercode_node(hass, test_client):
    """Test getting usercodes on node without usercodes."""
    app = mock_http_component_app(hass)
    ZWaveUserCodeView().register(app.router)

    network = hass.data[ZWAVE_NETWORK] = MagicMock()
    node = MockNode(node_id=18)

    network.nodes = {18: node}
    node.get_values.return_value = node.values

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/usercodes/18')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {}
コード例 #37
0
ファイル: test_html5.py プロジェクト: zzhmy/home-assistant
    def test_unregistering_device_view(self, loop, test_client):
        """Test that the HTML unregister view works."""
        hass = MagicMock()

        config = {
            'some device': SUBSCRIPTION_1,
            'other device': SUBSCRIPTION_2,
        }

        m = mock_open(read_data=json.dumps(config))
        with patch('homeassistant.util.json.open', m, create=True):
            hass.config.path.return_value = CONFIG_FILE
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]
            assert view.json_path == hass.config.path.return_value
            assert view.registrations == config

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            resp = yield from client.delete(REGISTER_URL,
                                            data=json.dumps({
                                                'subscription':
                                                SUBSCRIPTION_1['subscription'],
                                            }))

            config.pop('some device')

            assert resp.status == 200, resp.response
            assert view.registrations == config

            hass.async_add_job.assert_called_with(save_json, CONFIG_FILE,
                                                  config)
コード例 #38
0
def test_get_suites(hass, test_client):
    """Test getting suites."""
    app = mock_http_component_app(hass)

    with patch.dict(os.environ, {'FORCE_HASSBIAN': '1'}), \
            patch.object(config, 'SECTIONS', ['hassbian']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[HassbianSuitesView.name].register(app.router)

    client = yield from test_client(app)
    resp = yield from client.get('/api/config/hassbian/suites')
    assert resp.status == 200
    result = yield from resp.json()

    assert 'mosquitto' in result
    info = result['mosquitto']
    assert info['state'] == 'failed'
    assert info['description'] == \
        'Installs the Mosquitto package for setting up a local MQTT server'
コード例 #39
0
def test_get_suites(hass, test_client):
    """Test getting suites."""
    app = mock_http_component_app(hass)

    with patch.dict(os.environ, {'FORCE_HASSBIAN': '1'}), \
            patch.object(config, 'SECTIONS', ['hassbian']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[HassbianSuitesView.name].register(app.router)

    client = yield from test_client(app)
    resp = yield from client.get('/api/config/hassbian/suites')
    assert resp.status == 200
    result = yield from resp.json()

    assert 'mosquitto' in result
    info = result['mosquitto']
    assert info['state'] == 'failed'
    assert info['description'] == \
        'Installs the Mosquitto package for setting up a local MQTT server'
コード例 #40
0
def test_get_config(hass, test_client):
    """Test getting config on node."""
    app = mock_http_component_app(hass)
    ZWaveNodeConfigView().register(app.router)

    network = hass.data[ZWAVE_NETWORK] = MagicMock()
    node = MockNode(node_id=2)
    value = MockValue(index=12,
                      command_class=const.COMMAND_CLASS_CONFIGURATION)
    value.label = 'label'
    value.help = 'help'
    value.type = 'type'
    value.data = 'data'
    value.data_items = ['item1', 'item2']
    value.max = 'max'
    value.min = 'min'
    node.values = {12: value}
    network.nodes = {2: node}
    node.get_values.return_value = node.values

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/config/2')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {
        '12': {
            'data': 'data',
            'data_items': ['item1', 'item2'],
            'help': 'help',
            'label': 'label',
            'max': 'max',
            'min': 'min',
            'type': 'type'
        }
    }
コード例 #41
0
ファイル: test_html5.py プロジェクト: zzhmy/home-assistant
    def test_registering_new_device_fails_view(self, loop, test_client):
        """Test subs. are not altered when registering a new device fails."""
        hass = MagicMock()
        expected = {}

        hass.config.path.return_value = CONFIG_FILE
        html5.get_service(hass, {})
        view = hass.mock_calls[1][1][0]

        hass.loop = loop
        app = mock_http_component_app(hass)
        view.register(app.router)
        client = yield from test_client(app)
        hass.http.is_banned_ip.return_value = False

        hass.async_add_job.side_effect = HomeAssistantError()

        resp = yield from client.post(REGISTER_URL,
                                      data=json.dumps(SUBSCRIPTION_1))

        content = yield from resp.text()
        assert resp.status == 500, content
        assert view.registrations == expected
コード例 #42
0
    def test_registering_new_device_expiration_view(self, loop, test_client):
        """Test that the HTML view works."""
        hass = MagicMock()
        expected = {
            'unnamed device': SUBSCRIPTION_4,
        }

        m = mock_open()
        with patch('homeassistant.components.notify.html5.open',
                   m,
                   create=True):
            hass.config.path.return_value = 'file.conf'
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]
            assert view.json_path == hass.config.path.return_value
            assert view.registrations == {}

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False
            resp = yield from client.post(REGISTER_URL,
                                          data=json.dumps(SUBSCRIPTION_4))

            content = yield from resp.text()
            assert resp.status == 200, content
            assert view.registrations == expected
            handle = m()
            assert json.loads(handle.write.call_args[0][0]) == expected
コード例 #43
0
def test_get_usercodes_no_genreuser(hass, test_client):
    """Test getting usercodes on node missing genre user."""
    app = mock_http_component_app(hass)
    ZWaveUserCodeView().register(app.router)

    network = hass.data[ZWAVE_NETWORK] = MagicMock()
    node = MockNode(node_id=18,
                    command_classes=[const.COMMAND_CLASS_USER_CODE])
    value = MockValue(index=0, command_class=const.COMMAND_CLASS_USER_CODE)
    value.genre = const.GENRE_SYSTEM
    value.label = 'label'
    value.data = '1234'
    node.values = {0: value}
    network.nodes = {18: node}
    node.get_values.return_value = node.values

    client = yield from test_client(app)

    resp = yield from client.get('/api/zwave/usercodes/18')

    assert resp.status == 200
    result = yield from resp.json()

    assert result == {}
コード例 #44
0
def hassio_client(hassio_env, hass, test_client):
    """Create mock hassio http client."""
    app = mock_http_component_app(hass)
    hass.loop.run_until_complete(async_setup_component(hass, 'hassio', {}))
    hass.http.views['api:hassio'].register(app.router)
    yield hass.loop.run_until_complete(test_client(app))
コード例 #45
0
    def test_callback_view_with_jwt(self, loop, test_client):
        """Test that the notification callback view works with JWT."""
        hass = MagicMock()

        data = {
            'device': SUBSCRIPTION_1,
        }

        m = mock_open(read_data=json.dumps(data))
        with patch('homeassistant.components.notify.html5.open',
                   m,
                   create=True):
            hass.config.path.return_value = 'file.conf'
            with patch('homeassistant.components.notify.html5.os.path.isfile',
                       return_value=True):
                service = html5.get_service(hass, {'gcm_sender_id': '100'})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            with patch('pywebpush.WebPusher') as mock_wp:
                service.send_message('Hello',
                                     target=['device'],
                                     data={'icon': 'beer.png'})

            assert len(mock_wp.mock_calls) == 3

            # WebPusher constructor
            assert mock_wp.mock_calls[0][1][0] == \
                SUBSCRIPTION_1['subscription']
            # Third mock_call checks the status_code of the response.
            assert mock_wp.mock_calls[2][0] == '().send().status_code.__eq__'

            # Call to send
            push_payload = json.loads(mock_wp.mock_calls[1][1][0])

            assert push_payload['body'] == 'Hello'
            assert push_payload['icon'] == 'beer.png'

            view = hass.mock_calls[2][1][0]
            view.registrations = data

            bearer_token = "Bearer {}".format(push_payload['data']['jwt'])

            hass.loop = loop
            app = mock_http_component_app(hass)
            view.register(app.router)
            client = yield from test_client(app)
            hass.http.is_banned_ip.return_value = False

            resp = yield from client.post(
                PUBLISH_URL,
                data=json.dumps({
                    'type': 'push',
                }),
                headers={'Authorization': bearer_token})

            assert resp.status == 200
            body = yield from resp.json()
            assert body == {"event": "push", "status": "ok"}