-
-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathtemplate_render.py
More file actions
59 lines (45 loc) · 1.86 KB
/
Copy pathtemplate_render.py
File metadata and controls
59 lines (45 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import itertools
from curlify2 import curlify
from jinja2 import Environment, FileSystemLoader, PackageLoader
def render(template_path, context, is_external=False):
"""Controller function that handles the Jinja2 rending of the template."""
loader = _loader(is_external)
env = Environment(
loader=loader,
autoescape=True,
extensions=["jinja2_humanize_extension.HumanizeExtension"],
)
env.filters["curlify"] = curlify.to_curl
env.filters["render_body"] = render_body
env.filters["group_by_top_level_endpoint"] = group_by_top_level_endpoint
env.globals["is_bytes"] = lambda o: isinstance(o, bytes)
chosen_template = env.get_template(template_path)
return chosen_template.render(**context)
def _loader(is_external):
"""
Private function that either returns Jinja2 FileSystemLoader or the
PackageLoader.
"""
if is_external:
return FileSystemLoader(searchpath="./")
return PackageLoader("scanapi", "templates")
def render_body(request):
"""Render body according to its request content type."""
content_type = request.headers.get("Content-Type")
if content_type in ["application/json", "text/plain"]:
return request.body.decode()
return f"Cannot render. Unsupported content type: {content_type}."
def group_by_top_level_endpoint(results):
"""
Groups results by endpoint name
Args:
[iterator]: iterator of request results
Returns:
[iterator]: an iterator with tuples containing the endpoint name
and an iterator for all request results of that endpoint
"""
def by_top_level_endpoint_name(result):
endpoint_name = result["endpoint_name"]
root, *generations = endpoint_name.split("::")
return generations[0] if generations else root or "root"
return itertools.groupby(results, by_top_level_endpoint_name)