From ff7ba139b175ac362f1b94b326014a636e2342a4 Mon Sep 17 00:00:00 2001
From: Razvan Vass
 <ze28pyvo@i10stud5.informatik.uni-erlangen.de.informatik.uni-erlangen.de>
Date: Tue, 2 Apr 2024 20:28:55 +0200
Subject: [PATCH] Treat errors for load config from env and tests for it

---
 dashboards/upload.py           |  7 +++++++
 tests/test_dashboard_upload.py | 22 ++++++++++++++++++++++
 2 files changed, 29 insertions(+)
 create mode 100644 tests/test_dashboard_upload.py

diff --git a/dashboards/upload.py b/dashboards/upload.py
index ccb9fd3..2be7684 100644
--- a/dashboards/upload.py
+++ b/dashboards/upload.py
@@ -58,6 +58,12 @@ def load_config_from_env(env_path: str = ".env") -> Tuple[str, str]:
         dotenv.load_dotenv(env_path)
     grafana_api_key = os.getenv("GRAFANA_API_KEY")
     grafana_server = os.getenv("GRAFANA_SERVER")
+
+    if not grafana_api_key:
+        raise ValueError("GRAFANA_API_KEY is None or not defined in the .env file")
+    if not grafana_server:
+        raise ValueError("GRAFANA_SERVER is None or not defined in the .env file")
+
     return grafana_server, grafana_api_key
 
 
@@ -65,3 +71,4 @@ def upload_dashboard(dashboard: Dashboard, folder: int) -> None:
     grafana_server, grafana_api_key = load_config_from_env()
     dashboard_json = get_dashboard_json(dashboard, overwrite=True, folder=folder)
     upload_to_grafana(dashboard_json, grafana_server, grafana_api_key, verify=False)
+
diff --git a/tests/test_dashboard_upload.py b/tests/test_dashboard_upload.py
new file mode 100644
index 0000000..2caafef
--- /dev/null
+++ b/tests/test_dashboard_upload.py
@@ -0,0 +1,22 @@
+# Test case using pytest
+import pytest
+from dashboards.upload import load_config_from_env
+from unittest.mock import patch
+import os
+
+def test_load_config_from_env():
+    # Case 1: Test if function raises exception for missing GRAFANA_API_KEY
+    with pytest.raises(ValueError) as e:
+        load_config_from_env(env_path=".env")
+    assert str(e.value) == "GRAFANA_API_KEY is None or not defined in the .env file"
+
+    # Case 2: Test if function raises exception for missing GRAFANA_SERVER
+    with patch.dict(os.environ, {"GRAFANA_API_KEY": "api_key"}):
+        with pytest.raises(ValueError) as e:
+            load_config_from_env(env_path=".env")
+        assert str(e.value) == "GRAFANA_SERVER is None or not defined in the .env file"
+
+    # Case 3: Test if function returns expected values when both variables are defined
+    with patch.dict(os.environ, {"GRAFANA_API_KEY": "api_key", "GRAFANA_SERVER": "server_url"}):
+        result = load_config_from_env(env_path=".env")
+        assert result == ("server_url", "api_key")
\ No newline at end of file
-- 
GitLab