Example #1
0
    def test_calling_notify_from_script_loaded_from_yaml(self):
        """Test if we can call a notify from a script."""
        yaml_conf = """
service: notify.notify
data:
  data:
    push:
      sound: US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav
data_template:
  message: >
          Test 123 {{ 2 + 2 }}
"""

        with tempfile.NamedTemporaryFile() as fp:
            fp.write(yaml_conf.encode('utf-8'))
            fp.flush()
            conf = yaml.load_yaml(fp.name)

        script.call_from_config(self.hass, conf)
        self.hass.pool.block_till_done()
        self.assertTrue(len(self.events) == 1)
        assert {
            'message': 'Test 123 4',
            'target': None,
            'title': 'Home Assistant',
            'data': {
                'push': {
                    'sound': 'US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav'
                }
            }
        } == self.events[0].data
Example #2
0
 async def read(self):
     """Restore from yaml file."""
     learned_info = {}
     try:
         learned_dict = load_yaml(self._config_dir + LEARNING_STORAGE_YAML)
         learned_info = {
             device: dacite.from_dict(data_class=GoveeLearnedInfo,
                                      data=learned_dict[device])
             for device in learned_dict
         }
         _LOGGER.info(
             "Loaded learning information from %s.",
             self._config_dir + LEARNING_STORAGE_YAML,
         )
     except FileNotFoundError:
         _LOGGER.warning(
             "There is no %s file containing learned information about your devices. This is normal for first start of Govee integration.",
             self._config_dir + LEARNING_STORAGE_YAML,
         )
     except (
             dacite.DaciteError,
             TypeError,
             UnicodeDecodeError,
             yaml.YAMLError,
     ) as ex:
         _LOGGER.warning(
             "The %s file containing learned information about your devices is invalid: %s. Learning starts from scratch.",
             self._config_dir + LEARNING_STORAGE_YAML,
             ex,
         )
     return learned_info
Example #3
0
    def test_calling_notify_from_script_loaded_from_yaml_with_title(self):
        """Test if we can call a notify from a script."""
        yaml_conf = """
service: notify.notify
data:
  data:
    push:
      sound: US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav
data_template:
  title: Test
  message: >
          Test 123 {{ 2 + 2 }}
"""

        with tempfile.NamedTemporaryFile() as fp:
            fp.write(yaml_conf.encode('utf-8'))
            fp.flush()
            conf = yaml.load_yaml(fp.name)

        script.call_from_config(self.hass, conf)
        self.hass.pool.block_till_done()
        self.assertTrue(len(self.events) == 1)
        assert {
            'message': 'Test 123 4',
            'title': 'Test',
            'data': {
                'push': {
                    'sound':
                    'US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav'}}
        } == self.events[0].data
def validate_services(integration: Integration):
    """Validate services."""
    try:
        data = load_yaml(str(integration.path / "services.yaml"))
    except FileNotFoundError:
        # Find if integration uses services
        has_services = grep_dir(
            integration.path,
            "**/*.py",
            r"(hass\.services\.(register|async_register))|async_register_entity_service|async_register_admin_service",
        )

        if has_services:
            integration.add_error(
                "services", "Registers services but has no services.yaml")
        return
    except HomeAssistantError:
        integration.add_error("services", "Unable to load services.yaml")
        return

    try:
        SERVICES_SCHEMA(data)
    except vol.Invalid as err:
        integration.add_error(
            "services", f"Invalid services.yaml: {humanize_error(data, err)}")
Example #5
0
def validate_services(integration: Integration):
    """Validate services."""
    # Find if integration uses services
    has_services = grep_dir(integration.path, "**/*.py",
                            r"hass\.services\.(register|async_register)")

    if not has_services:
        return

    try:
        data = load_yaml(str(integration.path / "services.yaml"))
    except FileNotFoundError:
        integration.add_error("services",
                              "Registers services but has no services.yaml")
        return
    except HomeAssistantError:
        integration.add_error(
            "services", "Registers services but unable to load services.yaml")
        return

    try:
        SERVICES_SCHEMA(data)
    except vol.Invalid as err:
        integration.add_error(
            "services",
            "Invalid services.yaml: {}".format(humanize_error(data, err)))
Example #6
0
def removeNonUseConfig(path, type, st_device_list):
    tempDoc = util_yaml.load_yaml(path)
    removeKey = []
    for data in tempDoc:
        item = dict(data)
        try:
            if item['name'][0:3] == 'st_' and type == item['platform']:
                exist = False
                for stDevice in st_device_list:
                    name = item['name']
                    _name = "st_" + re.sub(
                        removeSpeacilChar, '_',
                        stDevice['id'].lower() + "_" + stDevice['dni'].lower())
                    if name == _name:
                        exist = True
                        break
                if exist == False:
                    removeKey.append(data)

        except:
            continue

    for key in removeKey:
        tempDoc.remove(key)
    if len(removeKey) > 0:
        logging.error("Updated >> " + path)
        save_yaml(path, tempDoc)
        return True

    return False
Example #7
0
def removeNonUseCustomize(path, st_device_list):
    tempDoc = util_yaml.load_yaml(path)
    removeKey = []
    for key, value in tempDoc.items():
        if key[0:10] == "switch.st_" or key[0:10] == "sensor.st_":
            exist = False
            for item in st_device_list:
                _name = key[10:].lower().replace(' ', '_')
                dni = re.sub(removeSpeacilChar, '_',
                             item['id'].lower() + "_" + item['dni'].lower())
                if dni == _name:
                    exist = True
                    break

            if exist == False:
                removeKey.append(key)

    for key in removeKey:
        tempDoc.pop(key)
    if len(removeKey) > 0:
        logging.error("Updated >> " + path)
        save_yaml(path, tempDoc)
        return True

    return False
    def mock_load_blueprint(self, path):
        if path != blueprint_path:
            assert False, f"Unexpected blueprint {path}"
            return orig_load(self, path)

        return models.Blueprint(yaml.load_yaml(data_path),
                                expected_domain=self.domain,
                                path=path)
Example #9
0
def _read(path):
    """Read YAML helper."""
    if not os.path.isfile(path):
        with open(path, 'w'):
            pass
        return {}

    return load_yaml(path)
Example #10
0
def _read(path):
    """Read YAML helper."""
    if not os.path.isfile(path):
        with open(path, 'w'):
            pass
        return {}

    return load_yaml(path)
Example #11
0
 def __init__(self, fname):
     """Initialize the device config.
     Args:
         fname (string): The filename of the yaml config to load."""
     _CONFIG_DIR = dirname(config_dir.__file__)
     self._fname = fname
     filename = join(_CONFIG_DIR, fname)
     self._config = load_yaml(filename)
     _LOGGER.debug("Loaded device config %s", fname)
Example #12
0
    def load_services_files(yaml_files):
        """Load and parse services.yaml files."""
        loaded = {}
        for yaml_file in yaml_files:
            try:
                loaded[yaml_file] = load_yaml(yaml_file)
            except FileNotFoundError:
                loaded[yaml_file] = {}

        return loaded
    def load_services_files(yaml_files):
        """Load and parse services.yaml files."""
        loaded = {}
        for yaml_file in yaml_files:
            try:
                loaded[yaml_file] = load_yaml(yaml_file)
            except FileNotFoundError:
                loaded[yaml_file] = {}

        return loaded
Example #14
0
def load_yaml_config_file(config_path):
    """Parse a YAML configuration file."""
    conf_dict = load_yaml(config_path)

    if not isinstance(conf_dict, dict):
        _LOGGER.error(
            'The configuration file %s does not contain a dictionary',
            os.path.basename(config_path))
        raise HomeAssistantError()

    return conf_dict
Example #15
0
def load_yaml_config_file(config_path):
    """ Parse a YAML configuration file. """
    conf_dict = load_yaml(config_path)

    if not isinstance(conf_dict, dict):
        _LOGGER.error(
            'The configuration file %s does not contain a dictionary',
            os.path.basename(config_path))
        raise HomeAssistantError()

    return conf_dict
Example #16
0
    def _load_blueprint(self, blueprint_path) -> Blueprint:
        """Load a blueprint."""
        try:
            blueprint_data = yaml.load_yaml(
                self.hass.config.path(BLUEPRINT_FOLDER, self.domain,
                                      blueprint_path))
        except (HomeAssistantError, FileNotFoundError) as err:
            raise FailedToLoad(self.domain, blueprint_path, err) from err

        return Blueprint(blueprint_data,
                         expected_domain=self.domain,
                         path=blueprint_path)
Example #17
0
def isExistDevice(path, stData):
    deviceName = "st_" + re.sub(
        removeSpeacilChar, '_',
        stData['id'].lower() + "_" + stData['dni'].lower())
    type = stData['type']
    docs = util_yaml.load_yaml(path)
    for item in docs:
        for key, value in item.items():
            if key == "name" and value == deviceName:
                return True

    return False
Example #18
0
def _load_services_file(hass: HomeAssistant,
                        integration: Integration) -> JSON_TYPE:
    """Load services file for an integration."""
    try:
        return load_yaml(str(integration.file_path / "services.yaml"))
    except FileNotFoundError:
        _LOGGER.warning("Unable to find services.yaml for the %s integration",
                        integration.domain)
        return {}
    except HomeAssistantError:
        _LOGGER.warning("Unable to parse services.yaml for the %s integration",
                        integration.domain)
        return {}
Example #19
0
def test_default_blueprints(domain: str):
    """Validate a folder of blueprints."""
    integration = importlib.import_module(f"homeassistant.components.{domain}")
    blueprint_folder = pathlib.Path(
        integration.__file__).parent / BLUEPRINT_FOLDER
    items = list(blueprint_folder.glob("*"))
    assert len(items) > 0, "Folder cannot be empty"

    for fil in items:
        LOGGER.info("Processing %s", fil)
        assert fil.name.endswith(".yaml")
        data = yaml.load_yaml(fil)
        models.Blueprint(data, expected_domain=domain)
Example #20
0
 def lovelace_updated(event):
     url_path = event if isinstance(event,
                                    str) else event.data.get('url_path')
     if url_path == 'zhilace-type':
         data = make_type_lovelace(hass)
     elif url_path == 'zhilace-zone':
         data = make_zone_lovelace(hass)
     else:
         return
     path = hass.config.path(url_path + '.yaml')
     if (not os.path.exists(path)) if isinstance(
             event, str) else (load_yaml(path) != data):
         save_yaml(path, data)
Example #21
0
def load_yaml_config_file(config_path):
    """Parse a YAML configuration file.

    This method needs to run in an executor.
    """
    conf_dict = load_yaml(config_path)

    if not isinstance(conf_dict, dict):
        msg = 'The configuration file {} does not contain a dictionary'.format(
            os.path.basename(config_path))
        _LOGGER.error(msg)
        raise HomeAssistantError(msg)

    return conf_dict
Example #22
0
def load_yaml_config_file(config_path):
    """Parse a YAML configuration file.

    This method needs to run in an executor.
    """
    conf_dict = load_yaml(config_path)

    if not isinstance(conf_dict, dict):
        msg = 'The configuration file {} does not contain a dictionary'.format(
            os.path.basename(config_path))
        _LOGGER.error(msg)
        raise HomeAssistantError(msg)

    return conf_dict
Example #23
0
    def _load_blueprint(self, blueprint_path) -> Blueprint:
        """Load a blueprint."""
        try:
            blueprint_data = yaml.load_yaml(self.blueprint_folder / blueprint_path)
        except FileNotFoundError as err:
            raise FailedToLoad(
                self.domain,
                blueprint_path,
                FileNotFoundError(f"Unable to find {blueprint_path}"),
            ) from err
        except HomeAssistantError as err:
            raise FailedToLoad(self.domain, blueprint_path, err) from err

        return Blueprint(
            blueprint_data, expected_domain=self.domain, path=blueprint_path
        )
Example #24
0
    def _load_config(self, force):
        """Load the actual config."""
        fname = self.hass.config.path(LOVELACE_CONFIG_FILE)
        # Check for a cached version of the config
        if not force and self._cache is not None:
            config, last_update = self._cache
            modtime = os.path.getmtime(fname)
            if config and last_update > modtime:
                return config

        try:
            config = load_yaml(fname)
        except FileNotFoundError:
            raise ConfigNotFound from None

        self._cache = (config, time.time())
        return config
Example #25
0
    def _load_config(self, force):
        """Load the actual config."""
        fname = self.hass.config.path(LOVELACE_CONFIG_FILE)
        # Check for a cached version of the config
        if not force and self._cache is not None:
            config, last_update = self._cache
            modtime = os.path.getmtime(fname)
            if config and last_update > modtime:
                return config

        try:
            config = load_yaml(fname)
        except FileNotFoundError:
            raise ConfigNotFound from None

        self._cache = (config, time.time())
        return config
Example #26
0
    def _load_config(self, force):
        """Load the actual config."""
        # Check for a cached version of the config
        if not force and self._cache is not None:
            config, last_update = self._cache
            modtime = os.path.getmtime(self.path)
            if config and last_update > modtime:
                return False, config

        is_updated = self._cache is not None

        try:
            config = load_yaml(self.path)
        except FileNotFoundError:
            raise ConfigNotFound from None

        self._cache = (config, time.time())
        return is_updated, config
Example #27
0
def load_yaml_config_file(config_path):
    """Parse a YAML configuration file.

    This method needs to run in an executor.
    """
    try:
        conf_dict = load_yaml(config_path)
    except FileNotFoundError as err:
        raise HomeAssistantError("Config file not found: {}".format(
            getattr(err, 'filename', err)))

    if not isinstance(conf_dict, dict):
        msg = "The configuration file {} does not contain a dictionary".format(
            os.path.basename(config_path))
        _LOGGER.error(msg)
        raise HomeAssistantError(msg)

    return conf_dict
Example #28
0
def load_yaml_config_file(config_path):
    """Parse a YAML configuration file.

    This method needs to run in an executor.
    """
    try:
        conf_dict = load_yaml(config_path)
    except FileNotFoundError as err:
        raise HomeAssistantError("Config file not found: {}".format(
            getattr(err, 'filename', err)))

    if not isinstance(conf_dict, dict):
        msg = "The configuration file {} does not contain a dictionary".format(
            os.path.basename(config_path))
        _LOGGER.error(msg)
        raise HomeAssistantError(msg)

    return conf_dict
Example #29
0
def load_yaml_config_file(config_path: str) -> Dict[Any, Any]:
    """Parse a YAML configuration file.

    Raises FileNotFoundError or HomeAssistantError.

    This method needs to run in an executor.
    """
    conf_dict = load_yaml(config_path)

    if not isinstance(conf_dict, dict):
        msg = "The configuration file {} does not contain a dictionary".format(
            os.path.basename(config_path))
        _LOGGER.error(msg)
        raise HomeAssistantError(msg)

    # Convert values to dictionaries if they are None
    for key, value in conf_dict.items():
        conf_dict[key] = value or {}
    return conf_dict
Example #30
0
def load_yaml_config_file(config_path: str) -> Dict[Any, Any]:
    """Parse a YAML configuration file.

    This method needs to run in an executor.
    """
    try:
        conf_dict = load_yaml(config_path)
    except FileNotFoundError as err:
        raise HomeAssistantError("Config file not found: {}".format(
            getattr(err, 'filename', err)))

    if not isinstance(conf_dict, dict):
        msg = "The configuration file {} does not contain a dictionary".format(
            os.path.basename(config_path))
        _LOGGER.error(msg)
        raise HomeAssistantError(msg)

    # Convert values to dictionaries if they are None
    for key, value in conf_dict.items():
        conf_dict[key] = value or {}
    return conf_dict
Example #31
0
 def test_no_key(self):
     """Test item without an key."""
     files = {YAML_CONFIG_FILE: 'a: a\nnokeyhere'}
     with self.assertRaises(HomeAssistantError), \
             patch_yaml_files(files):
         yaml.load_yaml(YAML_CONFIG_FILE)
Example #32
0
 def load_services_file(yaml_file):
     """Load and cache a services.yaml file."""
     try:
         yaml_cache[yaml_file] = load_yaml(yaml_file)
     except FileNotFoundError:
         pass
Example #33
0
def test_no_key():
    """Test item without a key."""
    files = {YAML_CONFIG_FILE: "a: a\nnokeyhere"}
    with pytest.raises(HomeAssistantError), patch_yaml_files(files):
        yaml.load_yaml(YAML_CONFIG_FILE)
Example #34
0
def _read(path):
    """Read YAML helper."""
    if not os.path.isfile(path):
        return None

    return load_yaml(path)
Example #35
0
 def test_load_yaml_encoding_error(self, mock_open):
     """Test raising a UnicodeDecodeError."""
     mock_open.side_effect = UnicodeDecodeError('', b'', 1, 0, '')
     with pytest.raises(HomeAssistantError):
         yaml.load_yaml('test')
def _read(path):
    """Read YAML helper."""
    if not os.path.isfile(path):
        return None

    return load_yaml(path)
Example #37
0
def setup(hass, config):
    st_device_list = getSTDevice(config)

    app_url = config[DOMAIN].get('app_url')
    app_id = config[DOMAIN].get('app_id')
    access_token = config[DOMAIN].get('access_token')
    url = app_url + app_id + "/get?access_token=" + access_token

    configPath = hass.config.path(YAML_CONFIG_FILE)
    stream = open(configPath, "r")
    yaml.SafeLoader.add_constructor('!include', thing_constructor)

    docs = yaml.safe_load(stream)

    list = ["fan", "light", "switch"]

    isNeedToReboot = False

    customizePath = getCustomizePath(docs)
    if customizePath != "":
        customizePath = hass.config.path(customizePath)

    for item in st_device_list:
        file_path = findPath(hass.config, docs, item['type'])
        if file_path:
            exist = isExistDevice(file_path, item)
            if exist == False:
                target = None
                subDoc = util_yaml.load_yaml(file_path)
                target = None
                name = "st_" + re.sub(
                    removeSpeacilChar, '_',
                    (item['id'].lower() + "_" + item['dni'].lower()))
                if item['type'] == "sensor":
                    target = OrderedDict([
                        ("platform", "stsensor"), ("name", name),
                        ("resource", url + "&dni=" + item['dni']),
                        ("value_template", "{{ value_json.state }}"),
                        ("json_attributes", item['attr'])
                    ])
                elif item['type'] == "switch":
                    target = OrderedDict([
                        ("platform", "stswitch"), ("name", name),
                        ("resource", url + "&dni=" + item['dni']),
                        ("res_on", (url + "&dni=" + item['dni'] + "&turn=on")),
                        ("res_off",
                         (url + "&dni=" + item['dni'] + "&turn=off")),
                        ("json_attributes", item['attr'])
                    ])
                if target:
                    count = 0
                    for __item in subDoc:
                        count += 1

                    if count > 0:
                        logging.error("Added ST Device >> " + item['id'] +
                                      ", DeviceNetworkId=" + item['dni'])
                        isNeedToReboot = True
                        subDoc.append(target)
                        save_yaml(file_path, subDoc)
                    else:
                        dictlist = [target for x in range(1)]
                        save_yaml(file_path, dictlist)

                    if customizePath != "":
                        customizeDoc = util_yaml.load_yaml(customizePath)
                        tempName = item['type'] + "." + name
                        if isExistName(tempName, customizeDoc) == False:
                            customizeDoc.update(
                                {tempName: {
                                    'friendly_name': item['name']
                                }})
                            save_yaml(customizePath, customizeDoc)

    if customizePath != "":
        modified = removeNonUseCustomize(customizePath, st_device_list)
        if modified == True:
            isNeedToReboot = True

    switchConfigPath = getIncludeFilePath(hass.config, docs, "switch")
    if switchConfigPath != "":
        modified = removeNonUseConfig(switchConfigPath, "stswitch",
                                      st_device_list)
        if modified == True:
            isNeedToReboot = True

    sensorConfigPath = getIncludeFilePath(hass.config, docs, "sensor")
    if sensorConfigPath != "":
        modified = removeNonUseConfig(sensorConfigPath, "stsensor",
                                      st_device_list)
        if modified == True:
            isNeedToReboot = True

    if isNeedToReboot:
        logging.error("You must restart HA!!!")

    return True
Example #38
0
 def test_no_key(self):
     """Test item without an key."""
     files = {YAML_CONFIG_FILE: 'a: a\nnokeyhere'}
     with self.assertRaises(HomeAssistantError), \
             patch_yaml_files(files):
         yaml.load_yaml(YAML_CONFIG_FILE)
Example #39
0
def test_load_yaml_encoding_error(mock_open):
    """Test raising a UnicodeDecodeError."""
    mock_open.side_effect = UnicodeDecodeError('', b'', 1, 0, '')
    with pytest.raises(HomeAssistantError):
        yaml.load_yaml('test')