Skip to content

Commit b430d22

Browse files
authored
Merge pull request #12 from ZPascal/remove-src-folder-and-add-more-unittests
Add new tests and refactor the code
2 parents 5f0a041 + 0af272a commit b430d22

File tree

6 files changed

+82
-36
lines changed

6 files changed

+82
-36
lines changed
File renamed without changes.

src/grafana_dashboard/dashboard.py renamed to grafana_dashboard/dashboard.py

Lines changed: 51 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22
import sys
33
import json
44
import logging
5+
from typing import Dict
6+
import tempfile
57

68
import jinja2
79

8-
from src.grafana_dashboard.model import Model
10+
from .model import Model
911

1012

1113
class Dashboard:
@@ -23,18 +25,17 @@ def __init__(self, dashboard_model: Model):
2325
self.dashboard_model = dashboard_model
2426
self.logging = logging.Logger
2527

26-
def get_dashboard_json(self, template_values: dict) -> dict:
27-
"""The method includes a functionality to template the selected dashboard and return the corresponding dashboard
28-
as dictionary
28+
def get_dashboard_json(self, template_values: Dict) -> Dict:
29+
"""The method includes a functionality to template the selected dashboard and return the corresponding dashboard as dictionary
2930
3031
Args:
31-
template_values (dict): Specify the inserted templating values as dict
32+
template_values (Dict): Specify the inserted templating values as dict
3233
3334
Raises:
34-
Exception: Unspecified error by executing the functionality
35+
jinja2.TemplateNotFound: Jinja2 template not found
3536
3637
Returns:
37-
json_dashboard (dict): Returns the dashboard as dict
38+
json_dashboard (Dict): Returns the dashboard as dict
3839
"""
3940

4041
env = jinja2.Environment(loader=jinja2.FileSystemLoader("/"))
@@ -52,26 +53,59 @@ def get_dashboard_json(self, template_values: dict) -> dict:
5253
logging.error("Please define templating values.")
5354
sys.exit(1)
5455

55-
temp_path: str = "/tmp/dashboard.json"
56+
with tempfile.NamedTemporaryFile() as tmp_file:
57+
self.__write_tmp_dashboard_json(
58+
tmp_file.name, template_dashboard, template_values
59+
)
60+
return self.__get_dashboard_json(tmp_file.name)
61+
62+
@staticmethod
63+
def __write_tmp_dashboard_json(
64+
temp_path: str, template_dashboard: jinja2.Template, template_values: Dict
65+
):
66+
"""The method includes a functionality to write a templated json of the selected dashboard to a temporary file
67+
68+
Args:
69+
temp_path (str): Specify the temporary path as string
70+
template_dashboard (jinja2.Template): Specify the Jinja2 templated dashboard
71+
template_values (Dict): Specify the template values
72+
73+
Raises:
74+
FileNotFoundError: The corresponding temporary file is not available
75+
ValueError: There is an error inside the values
76+
AttributeError: You missed to add a specific attribute
77+
78+
Returns:
79+
None
80+
"""
5681

5782
try:
5883
fw = open(temp_path, "w")
5984
fw.write(template_dashboard.render(template_values))
6085
fw.close()
61-
except Exception as e:
86+
except (FileNotFoundError, ValueError, AttributeError) as e:
6287
logging.error(f"Please, check the error: {e} .")
6388
raise e
6489

65-
try:
66-
with open(temp_path) as file:
67-
json_dashboard = json.load(file)
68-
except Exception as e:
69-
logging.error(f"Please, check the error: {e} .")
70-
raise e
90+
@staticmethod
91+
def __get_dashboard_json(temp_path: str) -> Dict:
92+
"""The method includes a functionality to get the corresponding templated dashboard JSON as Dict
93+
94+
Args:
95+
temp_path (str): Specify the temporary path as string
96+
97+
Raises:
98+
FileNotFoundError: The corresponding temporary file is not available
99+
ValueError: There is an error inside the values
100+
101+
Returns:
102+
json_dashboard (Dict): Returns the dashboard JSON as dict
103+
"""
71104

72105
try:
73-
os.remove(temp_path)
74-
except Exception as e:
106+
with open(temp_path) as file:
107+
json_dashboard: Dict = json.load(file)
108+
except (FileNotFoundError, ValueError) as e:
75109
logging.error(f"Please, check the error: {e} .")
76110
raise e
77111

File renamed without changes.

setup.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
setuptools.setup(
77
name="grafana-dashboard-templater",
8-
version="1.0.1",
8+
version="1.0.2",
99
author="Pascal Zimmermann",
1010
author_email="[email protected]",
1111
description="A Grafana dashboard templater",
@@ -20,8 +20,7 @@
2020
"License :: OSI Approved",
2121
"Operating System :: OS Independent",
2222
],
23-
package_dir={"": "src"},
24-
packages=setuptools.find_packages(where="src"),
23+
packages=["grafana_dashboard"],
2524
install_requires=["jinja2"],
2625
python_requires=">=3.6",
2726
)

tests/test_dashboard.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import logging
22
import os
3-
import unittest
3+
import tempfile
4+
from unittest import TestCase
5+
from unittest.mock import MagicMock
46
import jinja2
57

6-
from src.grafana_dashboard.model import Model
7-
from src.grafana_dashboard.dashboard import Dashboard
8+
from grafana_dashboard.model import Model
9+
from grafana_dashboard.dashboard import Dashboard
810

911

10-
class DashboardTestCase(unittest.TestCase):
12+
class DashboardTestCase(TestCase):
1113
@staticmethod
1214
def __get_path_name() -> str:
1315
if os.path.basename(os.getcwd()) == "tests":
@@ -55,9 +57,7 @@ def test_get_dashboard_json_successful(self):
5557
self.assertEqual("test", dashboard["templating"]["list"][1]["current"]["text"])
5658

5759
def test_get_dashboard_json_no_config_template_error(self):
58-
template_path: str = (
59-
f"{os.path.dirname(os.getcwd())}{os.sep}dashboard"
60-
)
60+
template_path: str = f"{os.path.dirname(os.getcwd())}{os.sep}dashboard"
6161
test_model: Model = Model(template_path, "database", "postgresql", "v13")
6262
test_dashboard: Dashboard = Dashboard(test_model)
6363
with self.assertRaises(jinja2.TemplateNotFound):
@@ -73,6 +73,23 @@ def test_get_dashboard_json_no_template_values_error(self):
7373
with self.assertRaises(SystemExit):
7474
test_dashboard.get_dashboard_json({})
7575

76+
def test__write_tmp_dashboard_json_write_not_possible(self):
77+
template_path: str = DashboardTestCase.__get_path_name()
78+
test_model: Model = Model(template_path, "database", "postgresql", "v13")
79+
test_dashboard: Dashboard = Dashboard(test_model)
80+
81+
with self.assertRaises(AttributeError):
82+
with tempfile.NamedTemporaryFile() as tmp_file:
83+
test_dashboard._Dashboard__write_tmp_dashboard_json(
84+
tmp_file.name,
85+
MagicMock,
86+
{"app_name": "test", "prometheus_name": "test_name"},
87+
)
88+
89+
def test__get_dashboard_json_json_not_available(self):
90+
template_path: str = DashboardTestCase.__get_path_name()
91+
test_model: Model = Model(template_path, "database", "postgresql", "v13")
92+
test_dashboard: Dashboard = Dashboard(test_model)
7693

77-
if __name__ == "__main__":
78-
unittest.main()
94+
with self.assertRaises(FileNotFoundError):
95+
test_dashboard._Dashboard__get_dashboard_json("/tmp/dashboard1.json")

tests/test_model.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import unittest
1+
from unittest import TestCase
22

3-
from src.grafana_dashboard.model import Model
3+
from grafana_dashboard.model import Model
44

55

6-
class ModelTestCase(unittest.TestCase):
6+
class ModelTestCase(TestCase):
77
def test_model_successful(self):
88
test_model: Model = Model("test1", "test2", "test3", "test4")
99
self.assertEqual("test1", test_model.dashboard_templates_path)
@@ -17,7 +17,3 @@ def test_model_error(self):
1717
self.assertNotEqual("test2", test_model.dashboard_type)
1818
self.assertNotEqual("test3", test_model.dashboard_version)
1919
self.assertNotEqual("test4", test_model.dashboard_templates_path)
20-
21-
22-
if __name__ == "__main__":
23-
unittest.main()

0 commit comments

Comments
 (0)