1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3 4# Copyright (c) 2021-2024 Huawei Device Co., Ltd. 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16# 17 18# This file provides functions thar are responsible for loading test parameters 19# that are used in templates (yaml lists). 20 21import os.path as ospath 22from typing import Dict, List, Any 23from pathlib import Path 24import yaml 25 26from runner.plugins.ets.utils.constants import YAML_EXTENSIONS, LIST_PREFIX 27from runner.plugins.ets.utils.exceptions import InvalidFileFormatException 28from runner.utils import iter_files, read_file 29 30Params = Dict 31 32 33def load_params(dirpath: Path) -> Params: 34 """ 35 Loads all parameters for a directory 36 """ 37 result = {} 38 39 for filename, filepath in iter_files(dirpath, allowed_ext=YAML_EXTENSIONS): 40 name_without_ext, _ = ospath.splitext(filename) 41 if not name_without_ext.startswith(LIST_PREFIX): 42 raise InvalidFileFormatException(message="Lists of parameters must start with 'list.'", filepath=filepath) 43 listname = name_without_ext[len(LIST_PREFIX):] 44 params: List[Dict[str, Any]] = parse_yaml(filepath) 45 if not isinstance(params, list): 46 raise InvalidFileFormatException(message="Parameters list must be YAML array", filepath=filepath) 47 result[listname] = params 48 return result 49 50 51def parse_yaml(path: str) -> Any: 52 """ 53 Parses a single YAML list of parameters 54 """ 55 text = read_file(path) 56 try: 57 params = yaml.safe_load(text) 58 except Exception as common_exp: 59 raise InvalidFileFormatException( 60 message=f"Could not load YAML: {str(common_exp)}", 61 filepath=path) from common_exp 62 return params 63