def test_config_is_allowed_external_url():
    """Test is_allowed_external_url method."""
    config = ha.Config(None)
    config.allowlist_external_urls = [
        "http://x.com/",
        "https://y.com/bla/",
        "https://z.com/images/1.jpg/",
    ]

    valid = [
        "http://x.com/1.jpg",
        "http://x.com",
        "https://y.com/bla/",
        "https://y.com/bla/2.png",
        "https://z.com/images/1.jpg",
    ]
    for url in valid:
        assert config.is_allowed_external_url(url)

    invalid = [
        "https://a.co",
        "https://y.com/bla_wrong",
        "https://y.com/bla/../image.jpg",
        "https://z.com/images",
    ]
    for url in invalid:
        assert not config.is_allowed_external_url(url)
def test_config_as_dict():
    """Test as dict."""
    config = ha.Config(None)
    config.config_dir = "/test/ha-config"
    config.hass = MagicMock()
    type(config.hass.state).value = PropertyMock(return_value="RUNNING")
    expected = {
        "latitude": 0,
        "longitude": 0,
        "elevation": 0,
        CONF_UNIT_SYSTEM: METRIC_SYSTEM.as_dict(),
        "location_name": "Home",
        "time_zone": "UTC",
        "components": set(),
        "config_dir": "/test/ha-config",
        "whitelist_external_dirs": set(),
        "allowlist_external_dirs": set(),
        "allowlist_external_urls": set(),
        "version": __version__,
        "config_source": "default",
        "safe_mode": False,
        "state": "RUNNING",
        "external_url": None,
        "internal_url": None,
    }

    assert expected == config.as_dict()
def test_config_is_allowed_path():
    """Test is_allowed_path method."""
    config = ha.Config(None)
    with TemporaryDirectory() as tmp_dir:
        # The created dir is in /tmp. This is a symlink on OS X
        # causing this test to fail unless we resolve path first.
        config.allowlist_external_dirs = {os.path.realpath(tmp_dir)}

        test_file = os.path.join(tmp_dir, "test.jpg")
        with open(test_file, "w") as tmp_file:
            tmp_file.write("test")

        valid = [test_file, tmp_dir, os.path.join(tmp_dir, "notfound321")]
        for path in valid:
            assert config.is_allowed_path(path)

        config.allowlist_external_dirs = {"/home", "/var"}

        invalid = [
            "/hass/config/secure",
            "/etc/passwd",
            "/root/secure_file",
            "/var/../etc/passwd",
            test_file,
        ]
        for path in invalid:
            assert not config.is_allowed_path(path)

        with pytest.raises(AssertionError):
            config.is_allowed_path(None)
Beispiel #4
0
    def __init__(self, remote_api, local_api=None, loop=None):
        """Initalize the forward instance."""
        if not remote_api.validate_api():
            raise HomeAssistantError(
                "Remote API at {}:{} not valid: {}".format(
                    remote_api.host, remote_api.port, remote_api.status))

        self.remote_api = remote_api

        self.loop = loop or asyncio.get_event_loop()
        self.executor = ThreadPoolExecutor(max_workers=5)
        self.loop.set_default_executor(self.executor)
        self.loop.set_exception_handler(self._async_exception_handler)
        self._pending_tasks = []
        self._pending_sheduler = None

        self.bus = EventBus(remote_api, self)
        self.services = ha.ServiceRegistry(self)
        self.states = StateMachine(self.bus, self.loop, self.remote_api)
        self.config = ha.Config()
        # This is a dictionary that any component can store any data on.
        self.data = {}
        self.state = ha.CoreState.not_running
        self.exit_code = None
        self.config.api = local_api
Beispiel #5
0
async def test_migration_base_url(hass, hass_storage):
    """Test that we migrate base url to internal/external url."""
    config = ha.Config(hass)
    stored = {"version": 1, "data": {}}
    hass_storage[ha.CORE_STORAGE_KEY] = stored
    with patch.object(hass.bus, "async_listen_once") as mock_listen:
        # Empty config
        await config.async_load()
        assert len(mock_listen.mock_calls) == 0

        # With just a name
        stored["data"] = {"location_name": "Test Name"}
        await config.async_load()
        assert len(mock_listen.mock_calls) == 1

        # With external url
        stored["data"]["external_url"] = "https://example.com"
        await config.async_load()
        assert len(mock_listen.mock_calls) == 1

    # Test that the event listener works
    assert mock_listen.mock_calls[0][1][0] == EVENT_HOMEASSISTANT_START

    # External
    hass.config.api = Mock(deprecated_base_url="https://loaded-example.com")
    await mock_listen.mock_calls[0][1][1](None)
    assert config.external_url == "https://loaded-example.com"

    # Internal
    for internal in ("http://hass.local", "http://192.168.1.100:8123"):
        hass.config.api = Mock(deprecated_base_url=internal)
        await mock_listen.mock_calls[0][1][1](None)
        assert config.internal_url == internal
async def test_incorrect_internal_external_url(hass, hass_storage, caplog):
    """Test that we warn when detecting invalid internal/extenral url."""
    config = ha.Config(hass)

    hass_storage[ha.CORE_STORAGE_KEY] = {
        "version": 1,
        "data": {
            "internal_url": None,
            "external_url": None,
        },
    }
    await config.async_load()
    assert "Invalid external_url set" not in caplog.text
    assert "Invalid internal_url set" not in caplog.text

    hass_storage[ha.CORE_STORAGE_KEY] = {
        "version": 1,
        "data": {
            "internal_url": "https://community.home-assistant.io/profile",
            "external_url": "https://www.home-assistant.io/blue",
        },
    }
    await config.async_load()
    assert "Invalid external_url set" in caplog.text
    assert "Invalid internal_url set" in caplog.text
Beispiel #7
0
async def test_additional_data_in_core_config(hass, hass_storage):
    """Test that we can handle additional data in core configuration."""
    config = ha.Config(hass)
    hass_storage[ha.CORE_STORAGE_KEY] = {
        "version": 1,
        "data": {"location_name": "Test Name", "additional_valid_key": "value"},
    }
    await config.async_load()
    assert config.location_name == "Test Name"
Beispiel #8
0
    def __init__(self, remote_api, local_api=None):
        if not remote_api.validate_api():
            raise ha.HomeAssistantError(
                "Remote API at {}:{} not valid: {}".format(
                    remote_api.host, remote_api.port, remote_api.status))

        self.remote_api = remote_api

        self.pool = pool = ha.create_worker_pool()

        self.bus = EventBus(remote_api, pool)
        self.services = ha.ServiceRegistry(self.bus, pool)
        self.states = StateMachine(self.bus, self.remote_api)
        self.config = ha.Config()

        self.config.api = local_api
Beispiel #9
0
    def __init__(self, remote_api, local_api=None, loop=None):
        """Initalize the forward instance."""
        if not remote_api.validate_api():
            raise HomeAssistantError(
                "Remote API at {}:{} not valid: {}".format(
                    remote_api.host, remote_api.port, remote_api.status))

        self.remote_api = remote_api

        self.loop = loop or asyncio.get_event_loop()
        self.pool = ha.create_worker_pool()

        self.bus = EventBus(remote_api, self)
        self.services = ha.ServiceRegistry(self.bus, self.add_job, self.loop)
        self.states = StateMachine(self.bus, self.loop, self.remote_api)
        self.config = ha.Config()
        self.state = ha.CoreState.not_running

        self.config.api = local_api
def test_config_defaults():
    """Test config defaults."""
    hass = Mock()
    config = ha.Config(hass)
    assert config.hass is hass
    assert config.latitude == 0
    assert config.longitude == 0
    assert config.elevation == 0
    assert config.location_name == "Home"
    assert config.time_zone == dt_util.UTC
    assert config.internal_url is None
    assert config.external_url is None
    assert config.config_source == "default"
    assert config.skip_pip is False
    assert config.components == set()
    assert config.api is None
    assert config.config_dir is None
    assert config.allowlist_external_dirs == set()
    assert config.allowlist_external_urls == set()
    assert config.media_dirs == {}
    assert config.safe_mode is False
    assert config.legacy_templates is False
 def setUp(self):
     """Set up things to be run when tests are started."""
     self.config = ha.Config(None)
     assert self.config.config_dir is None
def test_config_path_with_dir_and_file():
    """Test get_config_path method."""
    config = ha.Config(None)
    config.config_dir = "/test/ha-config"
    assert config.path("dir", "test.conf") == "/test/ha-config/dir/test.conf"
Beispiel #13
0
 def setUp(self):  # pylint: disable=invalid-name
     """Setup things to be run when tests are started."""
     self.config = ha.Config()
     self.assertIsNone(self.config.config_dir)
Beispiel #14
0
 def setUp(self):  # pylint: disable=invalid-name
     """ things to be run when tests are started. """
     self.config = ha.Config()
Beispiel #15
0
 def __init__(self, conf_dir):
     """Init the config_dir."""
     self.config = core.Config()
     self.config.config_dir = conf_dir