|
| 1 | +from typing import Iterable |
| 2 | +from esdlvalidator.validation.functions import utils |
| 3 | +from esdlvalidator.validation.functions.function import FunctionFactory, FunctionCheck, FunctionDefinition, \ |
| 4 | + ArgDefinition, FunctionType, CheckResult |
| 5 | + |
| 6 | + |
| 7 | +@FunctionFactory.register(FunctionType.CHECK, "reference_count_in_range") |
| 8 | +class ReferenceCountInRange(FunctionCheck): |
| 9 | + |
| 10 | + def get_function_definition(self): |
| 11 | + return FunctionDefinition( |
| 12 | + "reference_count_in_range", |
| 13 | + "Check if the entity has a reference count in the specified range", |
| 14 | + [ |
| 15 | + ArgDefinition("referenceType", "An iterable reference type to be checked", True), |
| 16 | + ArgDefinition("min", "Minimum value of the range", True), |
| 17 | + ArgDefinition("max", "Maximum value of the range", True), |
| 18 | + ArgDefinition("resultMsgJSON", "Display output in JSON format", False) |
| 19 | + ] |
| 20 | + ) |
| 21 | + |
| 22 | + |
| 23 | + def execute(self): |
| 24 | + |
| 25 | + referenceType = self.args["referenceType"] |
| 26 | + if not isinstance(referenceType, str): |
| 27 | + raise ValueError(f"Invalid function argument. Argument 'referenceType' should be a string, got {type(referenceType)}") |
| 28 | + |
| 29 | + min = self.args["min"] |
| 30 | + max = self.args["max"] |
| 31 | + if not isinstance(min, int) or not isinstance(max, int): |
| 32 | + raise ValueError(f"Invalid function argument. Argument 'min' or 'max' should be an integer, got {type(min)}, {type(max)}") |
| 33 | + |
| 34 | + r = utils.get_attribute(self.value, referenceType) |
| 35 | + if r is None: |
| 36 | + raise ValueError(f"{self.value.id} ({self.value.name}) has no reference '{referenceType}'") |
| 37 | + if not isinstance(r, Iterable): |
| 38 | + raise ValueError(f"Reference '{referenceType}' is not iterable") |
| 39 | + |
| 40 | + msg = None |
| 41 | + if len(r) > max: |
| 42 | + msg = f"{self.value.id} ({self.value.name}) has {len(r)} {referenceType}, more than the allowed maximum ({max})" |
| 43 | + elif len(r) < min: |
| 44 | + msg = f"{self.value.id} ({self.value.name}) has {len(r)} {referenceType}, less than the allowed minimum ({min})" |
| 45 | + |
| 46 | + if msg: |
| 47 | + if 'resultMsgJSON' in self.args and self.args['resultMsgJSON']: |
| 48 | + result = { "offending_asset": self.value.id, "message": msg } |
| 49 | + return CheckResult(False, result) |
| 50 | + else: |
| 51 | + return CheckResult(False, msg) |
| 52 | + |
| 53 | + return CheckResult(True) |
0 commit comments