h2oaimichalmarszalek commited on
Commit
6181de0
·
1 Parent(s): b7a26b6

refactor to functor

Browse files
Files changed (1) hide show
  1. tools/helm_test_gen.py +79 -71
tools/helm_test_gen.py CHANGED
@@ -2,78 +2,86 @@ import re
2
  import yaml
3
  import os
4
  from typing import Optional
5
- from smolagents import tool
6
  from jinja2 import Environment, FileSystemLoader
7
  from pydash import py_
8
 
9
 
10
- SEP = '''
11
-
12
- ---
13
-
14
- '''
15
-
16
-
17
- def get_yaml_value(d: dict[str], xpath: str, default: Optional[str] = None) -> str:
18
- try:
19
- if '.' in xpath:
20
- h = xpath.split('.')[0]
21
- t = '.'.join(xpath.split('.')[1:])
22
- return get_yaml_value(d[h], t)
23
- else:
24
- return d[xpath]
25
- except Exception as ex:
26
- if default:
27
- return default
28
- else:
29
- raise ex
30
-
31
-
32
- def bool_to_str(value: bool) -> str:
33
- return str(value).lower()
34
-
35
-
36
- def get_object_by_kind(document: dict[str], kinds: tuple[str]) -> list[dict[str]]:
37
- return [*py_.filter_(document, lambda x: x['kind'] in kinds)]
38
-
39
-
40
- def get_envs_by_ref(container: dict[str], ref: str, name: str) -> list[dict[str]]:
41
- return [*py_.filter(container['env'], lambda x: x.get('valueFrom', {f'{ref}': {}}).get(f'{ref}', {'name': ''}).get('name') == name)] # noqa: E501
42
-
43
-
44
- def get_binding_subjects(subjects: dict[str], name: str) -> list[dict[str]]:
45
- return [*py_.filter(subjects, lambda x: x['name'] == name)]
46
-
47
-
48
- @tool
49
- def generate_helm_tests(document: str) -> str:
50
- """Generate Helm test scenarios from a Kubernetes YAML document.
51
-
52
- Args:
53
- document (str): A YAML string containing one or more Kubernetes resource definitions.
54
-
55
- Returns:
56
- str: A string containing the generated test scenarios, separated by a predefined
57
- separator when multiple resources are processed.
58
- """
59
- doc = [*yaml.safe_load_all(document)]
60
- result = ''
61
- current_dir = os.path.dirname(os.path.abspath(__file__))
62
- template_dir = os.path.join(current_dir, 'templates')
63
-
64
- for item in doc:
65
- name = item['metadata']['name']
66
- kind = item['kind']
67
- kindDesc = (re.sub(r'((?<=[a-z])[A-Z]|(?<!\A)[A-Z](?=[a-z]))', r' \1', kind)).lower()
68
- env = Environment(loader=FileSystemLoader(template_dir))
69
- env.globals['gyv'] = get_yaml_value
70
- env.globals['bool_to_str'] = bool_to_str
71
- env.globals['get_object_by_kind'] = get_object_by_kind
72
- env.globals['get_env_by_ref'] = get_envs_by_ref
73
- env.globals['get_binding_subjects'] = get_binding_subjects
74
- template = env.get_template('scenario.jinja')
75
- output = template.render(name=name, app='app', kind=kind, kindDesc=kindDesc, item=item, document=doc)
76
- if result:
77
- result += SEP
78
- result += output
79
- return result
 
 
 
 
 
 
 
 
 
2
  import yaml
3
  import os
4
  from typing import Optional
5
+ from smolagents import Tool
6
  from jinja2 import Environment, FileSystemLoader
7
  from pydash import py_
8
 
9
 
10
+ class GenerateHelmTest(Tool):
11
+ name = "generate_helm_tests"
12
+ description = "Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results."
13
+ inputs = {'document': {'type': 'string', 'description': 'A YAML string containing one or more Kubernetes resource definitions.'}}
14
+ output_type = "string"
15
+
16
+ SEP = '''
17
+
18
+ ---
19
+
20
+ '''
21
+
22
+
23
+ def get_yaml_value(self, d: dict[str], xpath: str, default: Optional[str] = None) -> str:
24
+ try:
25
+ if '.' in xpath:
26
+ h = xpath.split('.')[0]
27
+ t = '.'.join(xpath.split('.')[1:])
28
+ return self.get_yaml_value(d[h], t)
29
+ else:
30
+ return d[xpath]
31
+ except Exception as ex:
32
+ if default:
33
+ return default
34
+ else:
35
+ raise ex
36
+
37
+
38
+ @staticmethod
39
+ def bool_to_str(value: bool) -> str:
40
+ return str(value).lower()
41
+
42
+
43
+ @staticmethod
44
+ def get_object_by_kind(document: dict[str], kinds: tuple[str]) -> list[dict[str]]:
45
+ return [*py_.filter_(document, lambda x: x['kind'] in kinds)]
46
+
47
+ @staticmethod
48
+ def get_envs_by_ref(container: dict[str], ref: str, name: str) -> list[dict[str]]:
49
+ return [*py_.filter(container['env'], lambda x: x.get('valueFrom', {f'{ref}': {}}).get(f'{ref}', {'name': ''}).get('name') == name)] # noqa: E501
50
+
51
+ @staticmethod
52
+ def get_binding_subjects(subjects: dict[str], name: str) -> list[dict[str]]:
53
+ return [*py_.filter(subjects, lambda x: x['name'] == name)]
54
+
55
+
56
+
57
+ def forward(self, document: str) -> str:
58
+ """Generate Helm test scenarios from a Kubernetes YAML document.
59
+
60
+ Args:
61
+ document (str): A YAML string containing one or more Kubernetes resource definitions.
62
+
63
+ Returns:
64
+ str: A string containing the generated test scenarios, separated by a predefined
65
+ separator when multiple resources are processed.
66
+ """
67
+ doc = [*yaml.safe_load_all(document)]
68
+ result = ''
69
+ current_dir = os.path.dirname(os.path.abspath(__file__))
70
+ template_dir = os.path.join(current_dir, 'templates')
71
+
72
+ for item in doc:
73
+ name = item['metadata']['name']
74
+ kind = item['kind']
75
+ kindDesc = (re.sub(r'((?<=[a-z])[A-Z]|(?<!\A)[A-Z](?=[a-z]))', r' \1', kind)).lower()
76
+ env = Environment(loader=FileSystemLoader(template_dir))
77
+ env.globals['gyv'] = self.get_yaml_value
78
+ env.globals['bool_to_str'] = GenerateHelmTest.bool_to_str
79
+ env.globals['get_object_by_kind'] = GenerateHelmTest.get_object_by_kind
80
+ env.globals['get_env_by_ref'] = GenerateHelmTest.get_envs_by_ref
81
+ env.globals['get_binding_subjects'] = GenerateHelmTest.get_binding_subjects
82
+ template = env.get_template('scenario.jinja')
83
+ output = template.render(name=name, app='app', kind=kind, kindDesc=kindDesc, item=item, document=doc)
84
+ if result:
85
+ result += GenerateHelmTest.SEP
86
+ result += output
87
+ return result