diff --git a/dashboards/upload.py b/dashboards/upload.py index ccb9fd301fd27715e6136a70fe50e54b0dc5b73c..2be76847ef56997adf814f144c300569f2661bc9 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 0000000000000000000000000000000000000000..2caafef551e5598433832eed6e20e33bc6621ff0 --- /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