1#!/usr/bin/env python3 2# -- coding: utf-8 -- 3# 4# Copyright (c) 2024-2025 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 18from enum import Enum 19from typing import NoReturn, TypeVar 20 21from runner.common_exceptions import IncorrectEnumValue 22 23EnumT = TypeVar("EnumT", bound='BaseEnum') 24 25 26class BaseEnum(Enum): 27 28 @classmethod 29 def raise_incorrect_value(cls: type[EnumT], value: str, *, reason: str = '') -> NoReturn: 30 raise IncorrectEnumValue( 31 f'Incorrect value "{value}" for {reason if reason else cls.__name__}' 32 f'Expected one of: {cls.values()}') 33 34 @classmethod 35 def from_str(cls: type[EnumT], item_name: str) -> EnumT | None: 36 for enum_value in cls: 37 if enum_value.value.lower() == item_name.lower() or str(enum_value).lower() == item_name.lower(): 38 return enum_value 39 return None 40 41 @classmethod 42 def values(cls: type[EnumT]) -> list[str]: 43 member_map = "_member_map_" 44 if hasattr(cls, member_map): 45 return [str(cls[attr].value) for attr in getattr(cls, member_map)] 46 return [] 47 48 @classmethod 49 def is_value(cls: type[EnumT], value: str, option_name: str) -> EnumT: 50 enum_value = cls.from_str(value) 51 if enum_value is None: 52 cls.raise_incorrect_value(value, reason=f"parameter {option_name}") 53 return enum_value 54