Skip to content

Commit f6700b6

Browse files
committed
chore: add more tests for reporters and add handling of TemplateSyntaxError when loading a template in HTMLReporter
Signed-off-by: Trong Nhan Mai <[email protected]>
1 parent bdff292 commit f6700b6

File tree

5 files changed

+84
-43
lines changed

5 files changed

+84
-43
lines changed

src/macaron/output_reporter/reporter.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,12 @@ def __init__(
174174
self.template = self.env.get_template(target_template)
175175
except TemplateNotFound:
176176
logger.error("Cannot find the template to load.")
177+
except TemplateSyntaxError as error:
178+
location = f"line {error.lineno}"
179+
name = error.filename or error.name
180+
if name:
181+
location = f'File "{name}", {location}'
182+
logger.info("jinja2.TemplateSyntaxError: \n\t%s\n\t%s", error.message, location)
177183

178184
def _init_extensions(self) -> None:
179185
"""Dynamically add Jinja2 extension filters and tests."""
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{#
2+
Copyright (c) 2023 - 2023, Oracle and/or its affiliates. All rights reserved.
3+
Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
4+
#}
5+
6+
{# Trying to extract the undefined field will cause Jinja2 to raise a Runtime Exception. #}
7+
{{ data.undefined_key }}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{#
2+
Copyright (c) 2023 - 2023, Oracle and/or its affiliates. All rights reserved.
3+
Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
4+
#}
5+
6+
{# Missing a % #}
7+
{% if a }
8+
{% endif %}

tests/output_reporter/template.html renamed to tests/output_reporter/resources/template.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<!DOCTYPE html>
22
<html lang='en'>
33

4-
<!-- Copyright (c) 2022 - 2022, Oracle and/or its affiliates. All rights reserved. -->
4+
<!-- Copyright (c) 2022 - 2023, Oracle and/or its affiliates. All rights reserved. -->
55
<!-- Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/. -->
66

77
<head>

tests/output_reporter/test_reporter.py

Lines changed: 62 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"""
77

88
import os
9+
from pathlib import Path
910
from typing import Any
1011
from unittest.mock import MagicMock, call, patch
1112

@@ -20,8 +21,6 @@
2021

2122
from ..st import JINJA_CONTEXT_DICT
2223

23-
ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
24-
2524

2625
class MockRecord(Record):
2726
"""A mock class for the record."""
@@ -43,41 +42,52 @@ def get_dict(self) -> dict:
4342
return self.mock_data
4443

4544

46-
def test_no_html_template_found() -> None:
45+
@pytest.fixture(scope="module", name="custom_jinja_env")
46+
def fixture_custom_jinja_env() -> Environment:
47+
"""Return the custom Jinja2 environment for testing.
48+
49+
Returns
50+
-------
51+
Environment
52+
The custom Jinja2 environment.
53+
"""
54+
root_path = Path(__file__).parent.joinpath("resources")
55+
return Environment(
56+
loader=FileSystemLoader(root_path),
57+
autoescape=select_autoescape(enabled_extensions=["html", "j2"]),
58+
trim_blocks=True,
59+
lstrip_blocks=True,
60+
)
61+
62+
63+
def test_no_html_template_found(custom_jinja_env: Environment) -> None:
4764
"""Test initializing a HTMLReporter instance with a non-existing template."""
48-
no_template_reporter = HTMLReporter(target_template="not_exist_template.html")
65+
no_template_reporter = HTMLReporter(env=custom_jinja_env, target_template="not_exist_template.html")
4966
assert not no_template_reporter.template
5067

5168

52-
@given(mock_data=JINJA_CONTEXT_DICT, num_dep=st.integers(min_value=0, max_value=3))
53-
def test_gen_json_reports(mock_data: Any, num_dep: int) -> None:
54-
"""Test if JSONReporter can print JSON files without errors."""
55-
report = Report(MockRecord(mock_data))
56-
for _ in range(num_dep):
57-
report.root_record.dependencies.append(MockRecord(mock_data))
69+
def test_syntax_err_template(custom_jinja_env: Environment) -> None:
70+
"""Test generating the HTML report from a template with syntax errors."""
71+
syntax_err = HTMLReporter(env=custom_jinja_env, target_template="syntax_err.html")
72+
assert not syntax_err.template
5873

59-
reporter = JSONReporter()
6074

75+
def test_runtime_err_template(custom_jinja_env: Environment) -> None:
76+
"""Test generating the HTML report from a template with runtime errors."""
77+
report = Report(MockRecord({}))
78+
runtime_err = HTMLReporter(env=custom_jinja_env, target_template="runtime_err.html")
6179
with patch("builtins.open") as mock_open:
62-
reporter.generate("report_paths", report)
63-
calls = [call(os.path.join("report_paths", "dependencies.json"), mode="w", encoding="utf-8")]
64-
mock_open.assert_has_calls(calls)
80+
runtime_err.generate("report_paths", report)
81+
mock_open.assert_not_called()
6582

6683

6784
@given(mock_data=JINJA_CONTEXT_DICT, num_dep=st.integers(min_value=0, max_value=3))
68-
def test_gen_html_reports(mock_data: Any, num_dep: int) -> None:
85+
def test_gen_html_reports(custom_jinja_env: Environment, mock_data: Any, num_dep: int) -> None:
6986
"""Test if HTMLReporter can print HTML files without errors."""
7087
report = Report(MockRecord(mock_data))
7188
for _ in range(num_dep):
7289
report.root_record.dependencies.append(MockRecord(mock_data))
7390

74-
custom_jinja_env = Environment(
75-
loader=FileSystemLoader(ROOT_PATH),
76-
autoescape=select_autoescape(enabled_extensions=["html", "j2"]),
77-
trim_blocks=True,
78-
lstrip_blocks=True,
79-
)
80-
8191
reporter = HTMLReporter(env=custom_jinja_env, target_template="template.html")
8292
with patch("builtins.open") as mock_open:
8393
reporter.generate("report_paths", report)
@@ -97,8 +107,10 @@ def test_gen_html_reports(mock_data: Any, num_dep: int) -> None:
97107
(SCMStatus.AVAILABLE, True, False),
98108
],
99109
)
100-
def test_main_target_status(main_status: SCMStatus, has_deps: bool, gen_empty_main: bool) -> None:
101-
"""WIP"""
110+
def test_main_target_status(
111+
custom_jinja_env: Environment, main_status: SCMStatus, has_deps: bool, gen_empty_main: bool
112+
) -> None:
113+
"""Test the different scenarios for the main target's analysis status."""
102114
main_record: Record = Record(
103115
record_id="record",
104116
description="sample_desc",
@@ -110,28 +122,21 @@ def test_main_target_status(main_status: SCMStatus, has_deps: bool, gen_empty_ma
110122
policies_passed=[],
111123
)
112124

113-
dep_record: Record = Record(
114-
record_id="dep",
115-
description="sample_desc",
116-
pre_config=Configuration({}),
117-
status=SCMStatus.AVAILABLE,
118-
context=MagicMock(),
119-
dependencies=[],
120-
policies_failed=[],
121-
policies_passed=[],
122-
)
123-
124125
report = Report(main_record)
125126

126127
if has_deps:
127-
report.add_dep_record(dep_record)
128+
dep_record: Record = Record(
129+
record_id="dep",
130+
description="sample_desc",
131+
pre_config=Configuration({}),
132+
status=SCMStatus.AVAILABLE,
133+
context=MagicMock(),
134+
dependencies=[],
135+
policies_failed=[],
136+
policies_passed=[],
137+
)
138+
report.root_record.dependencies.append(dep_record)
128139

129-
custom_jinja_env = Environment(
130-
loader=FileSystemLoader(ROOT_PATH),
131-
autoescape=select_autoescape(enabled_extensions=["html", "j2"]),
132-
trim_blocks=True,
133-
lstrip_blocks=True,
134-
)
135140
reporter = HTMLReporter(env=custom_jinja_env, target_template="template.html")
136141
empty_main_call = call(os.path.join("report_paths", "index.html"), mode="w", encoding="utf-8")
137142
with patch("builtins.open") as mock_open:
@@ -140,3 +145,18 @@ def test_main_target_status(main_status: SCMStatus, has_deps: bool, gen_empty_ma
140145
mock_open.assert_has_calls([empty_main_call])
141146
else:
142147
assert empty_main_call.args not in mock_open.call_args_list
148+
149+
150+
@given(mock_data=JINJA_CONTEXT_DICT, num_dep=st.integers(min_value=0, max_value=3))
151+
def test_gen_json_reports(mock_data: Any, num_dep: int) -> None:
152+
"""Test if JSONReporter can print JSON files without errors."""
153+
report = Report(MockRecord(mock_data))
154+
for _ in range(num_dep):
155+
report.root_record.dependencies.append(MockRecord(mock_data))
156+
157+
reporter = JSONReporter()
158+
159+
with patch("builtins.open") as mock_open:
160+
reporter.generate("report_paths", report)
161+
calls = [call(os.path.join("report_paths", "dependencies.json"), mode="w", encoding="utf-8")]
162+
mock_open.assert_has_calls(calls)

0 commit comments

Comments
 (0)