diff --git a/examples/report/lic-5.json b/examples/report/lic-5.json new file mode 100644 index 0000000..16f01a7 --- /dev/null +++ b/examples/report/lic-5.json @@ -0,0 +1,46 @@ +{ + "license": { + "Logging Service": { + "authcode": null, + "custom": { + "_Log_Storage_TB": "7", + "logtype": "disk", + "alogging": "enabled" + }, + "description": "Device Logging Service", + "expired": "no", + "expires": "August 04, 2024", + "feature": "Logging Service", + "issued": "June 27, 2022", + "serial": "013201027229" + }, + "Y feature": { + "authcode": null, + "description": "Device Logging Service", + "expired": "no", + "expires": "August 04, 2024", + "feature": "Logging Service", + "issued": "June 29, 2022", + "serial": "013201027248" + }, + "PAN-DB URL Filtering": { + "Logging Service": "somehting", + "authcode": null, + "description": "Palo Alto Networks URL Filtering License", + "expired": "no", + "expires": "June 30, 2028", + "feature": "PAN-DB URL Filtering", + "issued": "April 27, 2023", + "serial": "013201027229" + }, + "C feature": { + "authcode": null, + "description": "Palo Alto Networks URL Filtering License", + "expired": "no", + "expires": "June 30, 2028", + "feature": "PAN-DB URL Filtering", + "issued": "April 27, 2023", + "serial": "013201027229" + } + } +} diff --git a/examples/report/lic-6.json b/examples/report/lic-6.json new file mode 100644 index 0000000..9121f59 --- /dev/null +++ b/examples/report/lic-6.json @@ -0,0 +1,45 @@ +{ + "license": { + "Logging Service": { + "authcode": null, + "custom": { + "_Log_Storage_TB": "9", + "logtype": "tape", + "blogging": "enabled" + }, + "description": "Device Logging Service", + "expired": "no", + "expires": "August 04, 2024", + "feature": "Logging Service", + "issued": "June 29, 2022", + "serial": "013201027229" + }, + "X feature": { + "authcode": null, + "description": "Device Logging Service", + "expired": "no", + "expires": "August 04, 2024", + "feature": "Logging Service", + "issued": "June 29, 2022", + "serial": "013201027248" + }, + "PAN-DB URL Filtering": { + "authcode": null, + "description": "Palo Alto Networks URL Filtering License", + "expired": "no", + "expires": "June 30, 2028", + "feature": "PAN-DB URL Filtering", + "issued": "April 29, 2023", + "serial": "013201027248" + }, + "C feature": { + "authcode": null, + "description": "Palo Alto Networks URL Filtering License", + "expired": "no", + "expires": "June 30, 2028", + "feature": "PAN-DB URL Filtering", + "issued": "April 27, 2023", + "serial": "013201027229" + } + } +} diff --git a/examples/report/snapshot_load_compare.py b/examples/report/snapshot_load_compare.py index 806631c..fa3aad6 100755 --- a/examples/report/snapshot_load_compare.py +++ b/examples/report/snapshot_load_compare.py @@ -25,49 +25,19 @@ def load_snap(fname: str) -> dict: # {"nics": {"count_change_threshold": 10}}, # {"license": {"properties": ["!serial"]}}, - # {"license": { - # "properties": ["!serial", "!issued", "!authcode", "!expires", "!custom", "non-existing"] # exclude higher level - # }}, - # {"license": { - # "properties": ["!serial", "!issued", "!authcode", "!expires", "non-existing", "!_Log_Storage_TB"] # works in multi-levels - # }}, - # {"license": { - # "properties": ["all"] - # }}, - # {"license": { - # "properties": ["!serial", "!issued", "!authcode", "!expires", "non-existing"] # invalid config is ignored and all is appended if all other are valid exclusions.. - # }}, - # {"license": { - # "properties": ["serial", "non-existing"] # compare only requested - # }}, - # {"license": { - # "properties": ["custom"] # if key exists in some sub-dicts, it will compare all the keys for the other dicts since this will be treated as non-existing key and ignored! NOTE: now it only ignores top level for added/missing - # }}, - # {"license": { - # "properties": ["!issued", "all"] # compare all except - # }}, - # {"license": { - # "properties": ["!issued", "serial"] # skip one and compare specific ones - # }}, + # NOTE lic-* files and below tests are added for testing during review - will be removed afterwards - # {"license": { - # "properties": ["Logging Service", "!custom"] # combination with parent - # }}, # "!license", # "license", - # {"license": { - # "properties": ["!Logging Service","!X feature"] - # }}, - ######## Top level keys - not intented but works # {"license": { # "properties": ["Logging Service"] # even works for parent level # }}, # {"license": { - # "properties": ["!Logging Service"] # even works for parent level + # "properties": ["!Logging Service"] # also support if property exists in different levels in different dicts # }}, # {"license": { - # "properties": ["issued", "PAN-DB URL Filtering"] # even works for parent level - but without multi level + # "properties": ["issued", "PAN-DB URL Filtering"] # multi-level "AND" operation (combination with parent) for properties is not supported on purpose - "PAN-DB URL Filtering" diff will be made for all its attributes since its the parent # }}, # {"license": { # "properties": ["X feature"] @@ -81,7 +51,7 @@ def load_snap(fname: str) -> dict: ######## 1st and 2nd level keys # {"license": { - # "properties": ["!_Log_Storage_TB"] # works.. + # "properties": ["!_Log_Storage_TB"] # works # }}, # {"license": { # "properties": ["_Log_Storage_TB"] # works @@ -90,6 +60,9 @@ def load_snap(fname: str) -> dict: # "properties": ["_Log_Storage_TB","issued"] # works # }}, # {"license": { + # "properties": ["issued", "!logtype"] # works + # }}, + # {"license": { # "properties": ["serial", "!logtype"] # works # }}, # {"license": { @@ -108,15 +81,22 @@ def load_snap(fname: str) -> dict: # "properties": ["something"] # since no such key is there it passes - works # }}, # {"license": { + # "properties": ["serial", "non-existing"] # works - compare only requested + # }}, + # {"license": { # "properties": ["all"] # works # }}, # {"license": { + # "properties": ["!issued", "all"] # works - compare all except + # }}, + # {"license": { # "properties": ["!logtype"] # works # }}, {"license": { "properties": ["!Logging Service", "issued"] # works }}, + # {"routes": {"properties": ["!flags"], "count_change_threshold": 10}}, # "!content_version", # { diff --git a/panos_upgrade_assurance/snapshot_compare.py b/panos_upgrade_assurance/snapshot_compare.py index 8fcf89c..522d2f3 100644 --- a/panos_upgrade_assurance/snapshot_compare.py +++ b/panos_upgrade_assurance/snapshot_compare.py @@ -227,49 +227,6 @@ def calculate_change_percentage( result["passed"] = False return result - - - # @staticmethod - # def get_all_keys(nested_dict): # NOTE keep it in snapshotcompare - # keys = [] - # for key, value in nested_dict.items(): - # keys.append(key) - # if isinstance(value, dict): - # keys.extend(SnapshotCompare.get_all_keys(value)) - # return keys - - @staticmethod - def is_key_comparison_allowed(key, properties): - """ - key str - properties List - """ - if properties is None: - return True - - if key in properties: - return True - elif ("!"+key) in properties: - return False - elif "all" in properties: - return True - elif all((element.startswith("!") for element in properties)): # all '!' or empty list - return True - - return False - - - @staticmethod - def is_key_excluded_in_properties(key, properties): - if properties is None: - return False - - if ("!"+key) in properties: - return True - - return False - - @staticmethod def calculate_diff_on_dicts( left_side_to_compare: Dict[str, Union[str, dict]], @@ -439,112 +396,55 @@ def calculate_diff_on_dicts( missing = left_side_to_compare.keys() - right_side_to_compare.keys() for key in missing: - if SnapshotCompare.is_key_comparison_allowed(key, properties): + if ConfigParser.is_element_included(key, properties): result["missing"]["missing_keys"].append(key) result["missing"]["passed"] = False - # if missing: - # result["missing"]["passed"] = False - # for key in missing: - # result["missing"]["missing_keys"].append(key) - added = right_side_to_compare.keys() - left_side_to_compare.keys() for key in added: - if SnapshotCompare.is_key_comparison_allowed(key, properties): + if ConfigParser.is_element_included(key, properties): result["added"]["added_keys"].append(key) result["added"]["passed"] = False - # if added: - # result["added"]["passed"] = False - # for key in added: - # result["added"]["added_keys"].append(key) - common_keys = left_side_to_compare.keys() & right_side_to_compare.keys() - if common_keys: - print("common keys:",common_keys) - # keys_to_check = ( - # ConfigParser(valid_elements=set(common_keys), - # requested_config=properties, - # ignore_invalid_config=True).prepare_config() - # if properties - # else common_keys - # ) - keys_to_check = common_keys # TODO - - item_changed = False - for key in keys_to_check: - print(f"Checking {key} in {left_side_to_compare}") - # if key == "PAN-DB URL Filtering": - # import pdb; pdb.set_trace() - - - if right_side_to_compare[key] != left_side_to_compare[key]: - if isinstance(left_side_to_compare[key], str): - - print(f"is key {key} comparison allowed with {properties}") - - if SnapshotCompare.is_key_comparison_allowed(key, properties): - result["changed"]["changed_raw"][key] = dict( - left_snap=left_side_to_compare[key], - right_snap=right_side_to_compare[key], - ) - item_changed = True - - elif isinstance(left_side_to_compare[key], dict): - - nested_keys_within_common_key = chain_unique_set(get_all_dict_keys(left_side_to_compare[key]), - get_all_dict_keys(right_side_to_compare[key])) - print("nested keys within common key:",nested_keys_within_common_key) - - # if is key excluded in properties - # continue - # - # if key in properties - # ##maybe remove key from properties - # ##if any nested key in properties; call with properties - # ##else call without properties - # recursive call without properties - DO NOT ALLOW MULTI LEVEL FILTERING.. - # - # if any nested key in properties - # ##filter properties in nested level - # recursive call - # - - if SnapshotCompare.is_key_excluded_in_properties(key, properties): # NOTE should check for exclude explicitly - continue # skip to the next key - - - if properties and key in properties: - # call without properties - DO NOT ALLOW MULTI LEVEL FILTERING.. - nested_results = SnapshotCompare.calculate_diff_on_dicts( - left_side_to_compare=left_side_to_compare[key], - right_side_to_compare=right_side_to_compare[key], - ) - else: - nested_results = SnapshotCompare.calculate_diff_on_dicts( - left_side_to_compare=left_side_to_compare[key], - right_side_to_compare=right_side_to_compare[key], - properties=properties, - ) - - # if any( - # SnapshotCompare.is_key_comparison_allowed(nested_key, properties) - # for nested_key in nested_keys_within_common_key - # ): - # nested_results = SnapshotCompare.calculate_diff_on_dicts( - # left_side_to_compare=left_side_to_compare[key], - # right_side_to_compare=right_side_to_compare[key], - # properties=properties, - # ) - - if nested_results: # TODO remove this - SnapshotCompare.calculate_passed(nested_results) - if not nested_results["passed"]: - result["changed"]["changed_raw"][key] = nested_results - item_changed = True + + item_changed = False + for key in common_keys: + if right_side_to_compare[key] != left_side_to_compare[key]: + if isinstance(left_side_to_compare[key], str): + if ConfigParser.is_element_included(key, properties): + result["changed"]["changed_raw"][key] = dict( + left_snap=left_side_to_compare[key], + right_snap=right_side_to_compare[key], + ) + item_changed = True + + elif isinstance(left_side_to_compare[key], dict): + nested_keys_within_common_key = chain_unique_set(get_all_dict_keys(left_side_to_compare[key]), + get_all_dict_keys(right_side_to_compare[key])) + if ConfigParser.is_element_explicit_excluded(key, properties): + continue # skip to the next key + + if properties and key in properties: + # call without properties - do not allow multi level (combined with parent) filtering.. + nested_results = SnapshotCompare.calculate_diff_on_dicts( + left_side_to_compare=left_side_to_compare[key], + right_side_to_compare=right_side_to_compare[key], + ) else: - raise exceptions.WrongDataTypeException(f"Unknown value format for key {key}.") - result["changed"]["passed"] = not item_changed + nested_results = SnapshotCompare.calculate_diff_on_dicts( + left_side_to_compare=left_side_to_compare[key], + right_side_to_compare=right_side_to_compare[key], + properties=properties, + ) + + SnapshotCompare.calculate_passed(nested_results) + if not nested_results["passed"]: + result["changed"]["changed_raw"][key] = nested_results + item_changed = True + else: + raise exceptions.WrongDataTypeException(f"Unknown value format for key {key}.") + result["changed"]["passed"] = not item_changed return result diff --git a/panos_upgrade_assurance/utils.py b/panos_upgrade_assurance/utils.py index 0160301..74928da 100644 --- a/panos_upgrade_assurance/utils.py +++ b/panos_upgrade_assurance/utils.py @@ -159,7 +159,6 @@ def __init__( self, valid_elements: Iterable, requested_config: Optional[List[Union[str, dict]]] = None, - ignore_invalid_config: Optional[bool] = False ): """ConfigParser constructor. @@ -171,17 +170,12 @@ def __init__( * `_requested_config_names` is introduced as `requested_config` stripped of any element configurations. Additionally, we do verification if all elements of this variable match `valid_elements`, if they do not, an exception is thrown by default. `request_config` is checked at top level level key in case of nested dictionaries within the list. - * if `ignore_invalid_config` is set to `True`, we ignore any invalid configurations passed in the `requested_config` - - (no exception thrown) and we remove these invalid configurations from `_requested_config_names` and - `requested_config`. # Parameters valid_elements (iterable): Valid elements against which we check the requested config. requested_config (list, optional): (defaults to `None`) A list of requested configuration items with an optional configuration. - ignore_invalid_config (bool, optional): (defaults to `False`) Whether to ignore invalid configurations in - `requested_config` or throw an exception. # Raises @@ -195,80 +189,49 @@ def __init__( self._requested_config_names = set(self._iter_extracted_config_names(self.requested_config)) self._requested_all_exclusive = self.is_all_exclusive(self._requested_config_names) - # self._requested_config_names = set( - # [ConfigParser._extract_element_name(config_keyword) for config_keyword in self.requested_config] - # ) - - non_existing_keys = set() for config_name in self._requested_config_names: if not self._is_element_valid(element=config_name): - non_existing_keys.add(config_name) - - if not ignore_invalid_config: # if invalid config is not accepted - if non_existing_keys: # and non existing keys found - raise exceptions.UnknownParameterException(f"Unknown configuration parameters passed: {non_existing_keys}.") - else: # invalid config is accepted - self._requested_config_names.difference_update(non_existing_keys) # remove non-existing keys - self._remove_invalid_requested_config(invalid_keys=non_existing_keys) - + raise exceptions.UnknownParameterException(f"Unknown configuration parameter passed: {config_name}.") else: self._requested_config_names = set(valid_elements) self.requested_config = list(valid_elements) # Meaning 'all' valid tests - - def _get_pure_element_name(self, element): - return element[1:] if element.startswith("!") else element + self._requested_all_exclusive = False @staticmethod def is_all_exclusive(config): """Method to check if all config elements are exclusive. - """ - if all((config_name.startswith("!") for config_name in config)): # TODO what to do for empty config - return True - - return False - - - def _is_element_valid(self, element: str) -> bool: - """Method verifying if a config element is a correct (supported) value. - - This method can also handle `not-elements` (see [`dialect`](/panos/docs/panos-upgrade-assurance/dialect)). - - # Parameters - - element (str): The config element to verify. This can be a `not-element`. This parameter is verified against - `self.valid_elements` `set`. Key word `'all'` is also accepted. - - # Returns - bool: `True` if the value is correct, `False` otherwise. + TODO docstring + Empty config also return True """ - if self._get_pure_element_name(element) in self.valid_elements: - return True - elif element == "all" and "all" in self.requested_config: + if all((config_name.startswith("!") for config_name in config)): return True - else: - return False + return False @staticmethod - def is_element_included(element, config): # TODO use for is_key_comparison_allowed + def is_element_included(element, config, all_exclusive_check=True): """Method verifying if a given element should be included according to the config list. + + TODO docstring """ if not config: # if config list is None or empty list it should be included return True if f"!{element}" in config: return False - elif ( element in config or "all" in config or ConfigParser.is_all_exclusive(config) ): + elif ( element in config or "all" in config ): + return True + elif all_exclusive_check and ConfigParser.is_all_exclusive(config): return True return False - @staticmethod def is_element_explicit_excluded(element, config): - """Method verifying if a given element should excluded. + """Method verifying if a given element should be excluded. + TODO docstring This method is required for snapshot comparison when we need to check if we should further compare nested dicts - it doesnot work to check with is_element_included for that case since nested dict key might not be included but nested keys might be subject to comparison @@ -278,15 +241,8 @@ def is_element_explicit_excluded(element, config): return False - def _iter_extracted_config_names(self, config): - """ - """ - for config_name in config: - yield ConfigParser._extract_element_name(config_name) - - @staticmethod - def _extract_element_name(config: Union[str, dict]) -> str: # TODO may change param name to config_element + def _extract_element_name(config_element: Union[str, dict]) -> str: """Method that extracts the name from a config element. If a config element is a string, the actual config element is returned. For elements of a dictionary type, the @@ -294,22 +250,22 @@ def _extract_element_name(config: Union[str, dict]) -> str: # TODO may change p # Parameters - config (str, dict): A config element to provide a name for. + config_element (str, dict): A config element to provide a name for. # Raises - WrongDataTypeException: Thrown when config does not meet requirements. + WrongDataTypeException: Thrown when config_element does not meet requirements. # Returns str: The config element name. """ - if isinstance(config, str): - return config - elif isinstance(config, dict): - if len(config) == 1: - return list(config.keys())[0] + if isinstance(config_element, str): + return config_element + elif isinstance(config_element, dict): + if len(config_element) == 1: + return list(config_element.keys())[0] else: raise exceptions.WrongDataTypeException( "Dict provided as config definition has incorrect format, it is supposed to have only one key {key:[]}" @@ -317,28 +273,49 @@ def _extract_element_name(config: Union[str, dict]) -> str: # TODO may change p else: raise exceptions.WrongDataTypeException("Config definition is neither string or dict") - def _remove_invalid_requested_config(self, invalid_keys: set) -> None: - """Remove invalid keys from the requested configuration (`self.requested_config`). + def _iter_extracted_config_names(self, config): + """ + TODO docstring + """ + for config_name in config: + yield ConfigParser._extract_element_name(config_name) - # Parameters + def _get_pure_element_name(self, element): + return element[1:] if element.startswith("!") else element - invalid_keys (set): A set of keys to remove from `self.requested_config`. + def _get_config_element_by_name(self, element): """ - for config_element in self.requested_config[:]: - if ConfigParser._extract_element_name(config_element) in invalid_keys: - self.requested_config.remove(config_element) + Return config element from requested_config by name + does not work for exclusion element + returns str or dict + TODO docstring + """ + if element in self.requested_config: + return element + else: + return next((config_element for config_element in self.requested_config + if isinstance(config_element, dict) and element in config_element), None) - def _expand_all(self) -> None: - """Expand key word `'all'` to `self.valid_elements`. + def _is_element_valid(self, element: str) -> bool: + """Method verifying if a config element is a correct (supported) value. - During expansion, elements from `self.valid_elements` which are already available in `self.requested_config` are skipped. - This way we do not introduce duplicates for elements that were provided explicitly. + This method can also handle `not-elements` (see [`dialect`](/panos/docs/panos-upgrade-assurance/dialect)). + + # Parameters + + element (str): The config element to verify. This can be a `not-element`. This parameter is verified against + `self.valid_elements` `set`. Key word `'all'` is also accepted. + + # Returns + bool: `True` if the value is correct, `False` otherwise. - This method directly operates on `self.requested_config`. """ - pure_names = set([self._get_pure_element_name(name) for name in self._requested_config_names if name != "all"]) - self.requested_config.extend(list(self.valid_elements - pure_names)) - self.requested_config.remove("all") + if self._get_pure_element_name(element) in self.valid_elements: + return True + elif element == "all" and "all" in self.requested_config: + return True + else: + return False def prepare_config(self) -> List[Union[str, dict]]: """Parse the input config and return a machine-usable configuration. @@ -351,41 +328,39 @@ def prepare_config(self) -> List[Union[str, dict]]: # Returns list: The parsed configuration. + # TODO docstring """ - # NOTE alternative approach to use is element included logic - # loop over valid elements and call is_element_included with self._requested_config_names as config param - # if element should be included; - # get element from original requested_config and put it to final config - # (need a seperate method for this to fetch config element with name if element is a dict) - # if element couldnot be found in requested_config put pure name in final config - # finally remove the 'all' keyword from requested_config if exists - - # with this approach we change the prepare config logic completely and dont use expand all - # but is element included has `is_all_exclusive` call inside and it can make performance worse - # to call it for each element. - - # for valid_element in self.valid_elements: - # if self.is_element_included(valid_element, self._requested_config_names): - # # get requested_config element with element name ?? - - ##### existing approach - # if self.is_all_exclusive(self._requested_config_names): - # self.requested_config.insert(0, "all") - - # # if all((config_name.startswith("!") for config_name in self._requested_config_names)): - # # self.requested_config.insert(0, "all") - - # if "all" in self.requested_config: - # self._expand_all() - - # final_configs = [] - - # for config_element in self.requested_config: - # if not ConfigParser._extract_element_name(config_element).startswith("!"): - # final_configs.append(config_element) + # TEMP NOTE for review - comments to be deleted + # alternative approach - if elements of valid_elements exist in requested config + # loop over valid elements + # if valid_element is excluded: + # continue (skip this element) + # elif all exclusive: + # add valid_element to final_config + # elif element is included (without all exclusive check) - empty or in config or all + # is_element_included is called with all exclusive check disabled to avoid a nested loop + # get element from original requested_config (via valid_element) and put it to final config + # else: + # continue (donot add element if not all exclusive and if element is not included) + final_configs = [] + + for valid_element in self.valid_elements: + if self.is_element_explicit_excluded(valid_element, self._requested_config_names): + continue + elif self._requested_all_exclusive: + final_configs.append(valid_element) + elif self.is_element_included(valid_element, self._requested_config_names, all_exclusive_check=False): + # get element from original requested_config (via valid_element) and put it to final config + config_element = self._get_config_element_by_name(valid_element) + if config_element is not None: + final_configs.append(config_element) + elif "all" in self.requested_config: + final_configs.append(valid_element) + else: + continue # donot add element if element is not included while not all exclusive - # return final_configs + return final_configs def interpret_yes_no(boolstr: str) -> bool: diff --git a/tests/test_utils.py b/tests/test_utils.py index 3a85a7b..6e4f7d8 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -8,6 +8,7 @@ valid_check_types = [v for k, v in vars(CheckType).items() if not k.startswith("__")] valid_snap_types = [v for k, v in vars(SnapType).items() if not k.startswith("__")] +# TODO update/add tests for the new is_element_included method which is different from is_element_valid class TestConfigParser: @pytest.mark.parametrize( @@ -39,7 +40,7 @@ def test_init_exception_unknown_parameter(self, valid_config_elements, requested """Check if exception is raised when ConfigParser is called with unknown param in requested config.""" with pytest.raises( UnknownParameterException, - match=r"Unknown configuration parameters passed: .*$", + match=r"Unknown configuration parameter passed: .*$", ): ConfigParser(valid_config_elements, requested_config) @@ -84,11 +85,11 @@ def test_init_no_requested_config(self, valid_config_elements, requested_config) def test_init_requested_config_names(self, requested_config, expected_requested_config_names, monkeypatch): """Check if ConfigParser sets _requested_config_names properly according to requested_config.""" - def _is_element_included_mock(*args, **kwargs): + def _is_element_valid_mock(*args, **kwargs): return True - # Overwrite _is_element_included - monkeypatch.setattr(ConfigParser, "_is_element_included", _is_element_included_mock) + # Overwrite _is_element_valid + monkeypatch.setattr(ConfigParser, "_is_element_valid", _is_element_valid_mock) parser = ConfigParser([], requested_config) # testing requested config - valid_elements is not important here assert parser._requested_config_names == set(expected_requested_config_names) # _requested_config_names is a set @@ -100,13 +101,13 @@ def _is_element_included_mock(*args, **kwargs): (valid_check_types, "!ntp_sync"), ], ) - def test__is_element_included_true(self, valid_config_elements, config_element, monkeypatch): + def test__is_element_valid_true(self, valid_config_elements, config_element, monkeypatch): """Check if method returns True for given config element in valid elements.""" monkeypatch.setattr(ConfigParser, "__init__", lambda _: None) parser = ConfigParser() parser.valid_elements = valid_config_elements - assert parser._is_element_included(config_element) # assert True + assert parser._is_element_valid(config_element) # assert True @pytest.mark.parametrize( "valid_config_elements, config_element", @@ -115,13 +116,13 @@ def test__is_element_included_true(self, valid_config_elements, config_element, (valid_check_types, "!not_valid_check"), ], ) - def test__is_element_included_false(self, valid_config_elements, config_element, monkeypatch): + def test__is_element_valid_false(self, valid_config_elements, config_element, monkeypatch): """Check if method returns False if given config element is not in valid elements.""" monkeypatch.setattr(ConfigParser, "__init__", lambda _: None) parser = ConfigParser() parser.valid_elements = valid_config_elements - assert not parser._is_element_included(config_element) # assert False + assert not parser._is_element_valid(config_element) # assert False @pytest.mark.parametrize( "valid_config_elements, config_element", @@ -130,14 +131,14 @@ def test__is_element_included_false(self, valid_config_elements, config_element, (valid_snap_types, "all"), ], ) - def test__is_element_included_all(self, valid_config_elements, config_element, monkeypatch): + def test__is_element_valid_all(self, valid_config_elements, config_element, monkeypatch): """Check if method returns True for all keyword with different valid elements.""" monkeypatch.setattr(ConfigParser, "__init__", lambda _: None) parser = ConfigParser() parser.valid_elements = valid_config_elements parser.requested_config = ["all"] - assert parser._is_element_included(config_element) # assert True + assert parser._is_element_valid(config_element) # assert True @pytest.mark.parametrize( "config_element, expected", @@ -208,12 +209,12 @@ def test_prepare_config_insert_all(self, requested_config, requested_config_all_ def _expand_all_mock(*args, **kwargs): pass - def _is_element_included_mock(*args, **kwargs): + def _is_element_valid_mock(*args, **kwargs): return True - # Overwrite _is_element_included and _expand_all + # Overwrite _is_element_valid and _expand_all monkeypatch.setattr(ConfigParser, "_expand_all", _expand_all_mock) - monkeypatch.setattr(ConfigParser, "_is_element_included", _is_element_included_mock) + monkeypatch.setattr(ConfigParser, "_is_element_valid", _is_element_valid_mock) parser = ConfigParser([], requested_config) # testing requested config - valid_elements is not important here parser.prepare_config() @@ -235,11 +236,11 @@ def _is_element_included_mock(*args, **kwargs): def test_prepare_config_call_expand_all(self, requested_config, monkeypatch): """Check if _expand_all is called when there is "all" keyword in requested config or all elements are exclusions.""" - def _is_element_included_mock(*args, **kwargs): + def _is_element_valid_mock(*args, **kwargs): return True - # Overwrite _is_element_included - monkeypatch.setattr(ConfigParser, "_is_element_included", _is_element_included_mock) + # Overwrite _is_element_valid + monkeypatch.setattr(ConfigParser, "_is_element_valid", _is_element_valid_mock) parser = ConfigParser([], requested_config) # testing requested config - valid_elements is not important here parser._expand_all = MagicMock() @@ -270,11 +271,11 @@ def test_prepare_config_dont_call_expand_all(self, requested_config, monkeypatch or all elements are not exclusions. """ - def _is_element_included_mock(*args, **kwargs): + def _is_element_valid_mock(*args, **kwargs): return True - # Overwrite _is_element_included - monkeypatch.setattr(ConfigParser, "_is_element_included", _is_element_included_mock) + # Overwrite _is_element_valid + monkeypatch.setattr(ConfigParser, "_is_element_valid", _is_element_valid_mock) parser = ConfigParser([], requested_config) # testing requested config - valid_elements is not important here parser._expand_all = MagicMock()