[VVP] Fixed issue in unused parameter detection
[vvp/validation-scripts.git] / ice_validator / tests / helpers.py
1 # -*- coding: utf8 -*-
2 # ============LICENSE_START====================================================
3 # org.onap.vvp/validation-scripts
4 # ===================================================================
5 # Copyright © 2019 AT&T Intellectual Property. All rights reserved.
6 # ===================================================================
7 #
8 # Unless otherwise specified, all software contained herein is licensed
9 # under the Apache License, Version 2.0 (the "License");
10 # you may not use this software except in compliance with the License.
11 # You may obtain a copy of the License at
12 #
13 #             http://www.apache.org/licenses/LICENSE-2.0
14 #
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS,
17 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 # See the License for the specific language governing permissions and
19 # limitations under the License.
20 #
21 #
22 #
23 # Unless otherwise specified, all documentation contained herein is licensed
24 # under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25 # you may not use this documentation except in compliance with the License.
26 # You may obtain a copy of the License at
27 #
28 #             https://creativecommons.org/licenses/by/4.0/
29 #
30 # Unless required by applicable law or agreed to in writing, documentation
31 # distributed under the License is distributed on an "AS IS" BASIS,
32 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 # See the License for the specific language governing permissions and
34 # limitations under the License.
35 #
36 # ============LICENSE_END============================================
37 #
38 #
39
40 """Helpers
41 """
42
43 import os
44 import re
45 from collections import defaultdict
46
47 from boltons import funcutils
48 from tests import cached_yaml as yaml
49
50 VERSION = "1.1.0"
51
52
53 def check_basename_ending(template_type, basename):
54     """
55     return True/False if the template type is matching
56     the filename
57     """
58     if not template_type:
59         return True
60     elif template_type == "volume":
61         return basename.endswith("_volume")
62     else:
63         return not basename.endswith("_volume")
64
65
66 def get_parsed_yml_for_yaml_files(yaml_files, sections=None):
67     """
68     get the parsed yaml for a list of yaml files
69     """
70     sections = [] if sections is None else sections
71     parsed_yml_list = []
72     for yaml_file in yaml_files:
73         try:
74             with open(yaml_file) as fh:
75                 yml = yaml.load(fh)
76         except yaml.YAMLError as e:
77             # pylint: disable=superfluous-parens
78             print("Error in %s: %s" % (yaml_file, e))
79             continue
80         if yml:
81             if sections:
82                 for k in yml.keys():
83                     if k not in sections:
84                         del yml[k]
85             parsed_yml_list.append(yml)
86     return parsed_yml_list
87
88
89 def validates(*requirement_ids):
90     """Decorator that tags the test function with one or more requirement IDs.
91
92     Example:
93         >>> @validates('R-12345', 'R-12346')
94         ... def test_something():
95         ...     pass
96         >>> assert test_something.requirement_ids == ['R-12345', 'R-12346']
97     """
98     # pylint: disable=missing-docstring
99     def decorator(func):
100         # NOTE: We use a utility here to ensure that function signatures are
101         # maintained because pytest inspects function signatures to inject
102         # fixtures.  I experimented with a few options, but this is the only
103         # library that worked. Other libraries dynamically generated a
104         # function at run-time, and then lost the requirement_ids attribute
105         @funcutils.wraps(func)
106         def wrapper(*args, **kw):
107             return func(*args, **kw)
108
109         wrapper.requirement_ids = requirement_ids
110         return wrapper
111
112     decorator.requirement_ids = requirement_ids
113     return decorator
114
115
116 def categories(*categories):
117     def decorator(func):
118         @funcutils.wraps(func)
119         def wrapper(*args, **kw):
120             return func(*args, **kw)
121
122         wrapper.categories = categories
123         return wrapper
124
125     decorator.categories = categories
126     return decorator
127
128
129 def get_environment_pair(heat_template):
130     """Returns a yaml/env pair given a yaml file"""
131     base_dir, filename = os.path.split(heat_template)
132     basename = os.path.splitext(filename)[0]
133     env_template = os.path.join(base_dir, "{}.env".format(basename))
134     if os.path.exists(env_template):
135         with open(heat_template, "r") as fh:
136             yyml = yaml.load(fh)
137         with open(env_template, "r") as fh:
138             eyml = yaml.load(fh)
139
140         environment_pair = {"name": basename, "yyml": yyml, "eyml": eyml}
141         return environment_pair
142
143     return None
144
145
146 def find_environment_file(yaml_files):
147     """
148     Pass file and recursively step backwards until environment file is found
149
150     :param yaml_files: list or string, start at size 1 and grows recursively
151     :return: corresponding environment file for a file, or None
152     """
153     # sanitize
154     if isinstance(yaml_files, str):
155         yaml_files = [yaml_files]
156
157     yaml_file = yaml_files[-1]
158     filepath, filename = os.path.split(yaml_file)
159
160     environment_pair = get_environment_pair(yaml_file)
161     if environment_pair:
162         return environment_pair
163
164     for file in os.listdir(filepath):
165         fq_name = "{}/{}".format(filepath, file)
166         if fq_name.endswith("yaml") or fq_name.endswith("yml"):
167             if fq_name not in yaml_files:
168                 with open(fq_name) as f:
169                     yml = yaml.load(f)
170                 resources = yml.get("resources", {})
171                 for resource_id, resource in resources.items():
172                     resource_type = resource.get("type", "")
173                     if resource_type == "OS::Heat::ResourceGroup":
174                         resource_type = (
175                             resource.get("properties", {})
176                             .get("resource_def", {})
177                             .get("type", "")
178                         )
179                     # found called nested file
180                     if resource_type == filename:
181                         yaml_files.append(fq_name)
182                         environment_pair = find_environment_file(yaml_files)
183
184     return environment_pair
185
186
187 def load_yaml(yaml_file):
188     """
189     Load the YAML file at the given path.  If the file has previously been
190     loaded, then a cached version will be returned.
191
192     :param yaml_file: path to the YAML file
193     :return: data structure loaded from the YAML file
194     """
195     with open(yaml_file) as fh:
196         return yaml.load(fh)
197
198
199 def traverse(data, search_key, func, path=None):
200     """
201     Traverse the data structure provided via ``data`` looking for occurences
202     of ``search_key``.  When ``search_key`` is found, the value associated
203     with that key is passed to ``func``
204
205     :param data:        arbitrary data structure of dicts and lists
206     :param search_key:  key field to search for
207     :param func:        Callable object that takes two parameters:
208                         * A list representing the path of keys to search_key
209                         * The value associated with the search_key
210     """
211     path = [] if path is None else path
212     if isinstance(data, dict):
213         for key, value in data.items():
214             curr_path = path + [key]
215             if key == search_key:
216                 func(curr_path, value)
217             traverse(value, search_key, func, curr_path)
218     elif isinstance(data, list):
219         for value in data:
220             curr_path = path + [value]
221             if isinstance(value, (dict, list)):
222                 traverse(value, search_key, func, curr_path)
223             elif value == search_key:
224                 func(curr_path, value)
225
226
227 def check_indices(pattern, values, value_type):
228     """
229     Checks that indices associated with the matched prefix start at 0 and
230     increment by 1.  It returns a list of messages for any prefixes that
231     violate the rules.
232
233     :param pattern: Compiled regex that whose first group matches the prefix and
234                     second group matches the index
235     :param values:  sequence of string names that may or may not match the pattern
236     :param name:    Type of value being checked (ex: IP Parameters). This will
237                     be included in the error messages.
238     :return:        List of error messages, empty list if no violations found
239     """
240     if not hasattr(pattern, "match"):
241         raise RuntimeError("Pattern must be a compiled regex")
242
243     prefix_indices = defaultdict(set)
244     for value in values:
245         m = pattern.match(value)
246         if m:
247             prefix_indices[m.group(1)].add(int(m.group(2)))
248
249     invalid_params = []
250     for prefix, indices in prefix_indices.items():
251         indices = sorted(indices)
252         if indices[0] != 0:
253             invalid_params.append(
254                 "{} with prefix {} do not start at 0".format(value_type, prefix)
255             )
256         elif len(indices) - 1 != indices[-1]:
257             invalid_params.append(
258                 (
259                     "Index values of {} with prefix {} do not " + "increment by 1: {}"
260                 ).format(value_type, prefix, indices)
261             )
262     return invalid_params
263
264
265 RE_BASE = re.compile(r"(^base$)|(^base_)|(_base_)|(_base$)")
266
267
268 def get_base_template_from_yaml_files(yaml_files):
269     """Return first filepath to match RE_BASE
270     """
271     for filepath in yaml_files:
272         basename = get_base_template_from_yaml_file(filepath)
273         if basename:
274             return basename
275     return None
276
277
278 def get_base_template_from_yaml_file(yaml_file):
279     (dirname, filename) = os.path.split(yaml_file)
280     files = os.listdir(dirname)
281     for file in files:
282         basename, __ = os.path.splitext(os.path.basename(file))
283         if (
284             (__ == ".yaml" or __ == ".yml")
285             and RE_BASE.search(basename)
286             and basename.find("volume") == -1
287         ):
288             return os.path.join(dirname, "{}{}".format(basename, __))
289     return None
290
291
292 def parameter_type_to_heat_type(parameter):
293     # getting parameter format
294     if isinstance(parameter, list):
295         parameter_type = "comma_delimited_list"
296     elif isinstance(parameter, str):
297         parameter_type = "string"
298     elif isinstance(parameter, dict):
299         parameter_type = "json"
300     elif isinstance(parameter, int):
301         parameter_type = "number"
302     elif isinstance(parameter, float):
303         parameter_type = "number"
304     elif isinstance(parameter, bool):
305         parameter_type = "boolean"
306     else:
307         parameter_type = None
308
309     return parameter_type
310
311
312 def prop_iterator(resource, *props):
313     terminators = ["get_resource", "get_attr", "str_replace", "get_param"]
314     if "properties" in resource:
315         resource = resource.get("properties")
316     props = list(props)
317
318     if isinstance(resource, dict) and any(x for x in terminators if x in resource):
319         yield resource
320     else:
321         prop = resource.get(props.pop(0))
322         if isinstance(prop, list):
323             for x in prop:
324                 yield from prop_iterator(x, *props)
325         elif isinstance(prop, dict):
326             yield from prop_iterator(prop, *props)
327
328
329 def get_param(property_value):
330     """
331     Returns the first parameter name from a get_param or None if get_param is
332     not used
333     """
334     if property_value and isinstance(property_value, dict):
335         param = property_value.get("get_param")
336         if param and isinstance(param, list) and len(param) > 0:
337             return param[0]
338         else:
339             return param
340     return None