Best Python code snippet using lisa_python
variable.py
Source:variable.py  
...168                    path = replace_variables(entry.file, current_variables)169                    loaded_variables = _load_from_file(path, is_secret=entry.is_secret)170                else:171                    value = replace_variables(entry.value, current_variables)172                    loaded_variables = load_from_variable_entry(173                        entry.name,174                        value,175                        is_case_visible=entry.is_case_visible,176                        is_secret=entry.is_secret,177                        mask=entry.mask,178                    )179                merge_variables(current_variables, loaded_variables)180                merge_variables(current_variables, higher_level_variables)181                is_current_updated = True182                left_variables.remove(entry)183        if undefined_variables:184            raise LisaException(f"variables are undefined: {undefined_variables}")185    return current_variables186def _load_from_file(187    file_name: str,188    is_secret: bool = False,189) -> Dict[str, VariableEntry]:190    results: Dict[str, VariableEntry] = {}191    if is_secret:192        secret.add_secret(file_name, secret.PATTERN_FILENAME)193    path = constants.RUNBOOK_PATH.joinpath(file_name)194    if path.suffix.lower() not in [".yaml", ".yml"]:195        raise LisaException("variable support only yaml and yml")196    try:197        with open(path, "r") as fp:198            raw_variables = yaml.safe_load(fp)199    except FileNotFoundError:200        raise FileNotFoundError(f"cannot find variable file: {path}")201    if not isinstance(raw_variables, Dict):202        raise LisaException("variable file must be dict")203    for key, raw_value in raw_variables.items():204        try:205            entry = convert_to_variable_entry(raw_value, is_secret=is_secret)206            raw_value = entry.value207            is_secret = is_secret or entry.is_secret208            is_case_visible = entry.is_case_visible209            mask = entry.mask210        except AssertionError:211            # if parsing is failed, regard the raw_value as a value.212            is_case_visible = False213            mask = ""214        results.update(215            load_from_variable_entry(216                key,217                raw_value=raw_value,218                is_secret=is_secret,219                is_case_visible=is_case_visible,220                mask=mask,221            )222        )223    return results224def get_case_variables(variables: Dict[str, VariableEntry]) -> Dict[str, Any]:225    return {226        name: value.data for name, value in variables.items() if value.is_case_visible227    }228def add_secrets_from_pairs(229    raw_pairs: Optional[List[str]],230) -> Dict[str, VariableEntry]:231    """232    Given a list of command line style pairs of [s]:key:value tuples,233    take the ones prefixed with "s:" and make them recorded234    secrets. At the end, also return a dictionary of those tuples235    (still with raw values).236    """237    results: Dict[str, VariableEntry] = {}238    if raw_pairs is None:239        return results240    for raw_pair in raw_pairs:241        is_secret = False242        if raw_pair.lower().startswith("s:"):243            is_secret = True244            raw_pair = raw_pair[2:]245        try:246            key, value = raw_pair.split(":", 1)247        except Exception as identifier:248            raise LisaException(249                f"failed on parsing variable '{raw_pair}'. The right format is "250                f"like name:value. If there is whitespace in the value, quote "251                f'the whole string like "name:value has whitespace". If It\'s a '252                'secret variable, follow the formant "s:name:value"'253                f"The raw error: {identifier}"254            )255        _add_variable(key, value, results, is_secret=is_secret)256    return results257def convert_to_variable_entry(258    raw_value: Any, is_secret: bool = False259) -> schema.Variable:260    assert isinstance(raw_value, dict), f"actual {type(raw_value)}"261    entry = schema.load_by_type(schema.Variable, raw_value)262    entry.is_secret = is_secret or entry.is_secret263    return entry264def load_from_variable_entry(265    name: str,266    raw_value: Any,267    is_secret: bool = False,268    is_case_visible: bool = False,269    mask: str = "",270) -> Dict[str, VariableEntry]:271    assert isinstance(name, str), f"actual: {type(name)}"272    results: Dict[str, VariableEntry] = {}273    if type(raw_value) in [str, int, bool, float, list, dict, type(None)]:274        value = raw_value275    elif isinstance(raw_value, schema.Variable):276        value = raw_value.value277        is_secret = raw_value.is_secret278        is_case_visible = raw_value.is_case_visible...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
