summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorПавел Жуков <33721692+LeaveMyYard@users.noreply.github.com>2023-05-26 11:55:15 +0300
committerПавел Жуков <33721692+LeaveMyYard@users.noreply.github.com>2023-05-26 11:55:15 +0300
commitff3be4a24d4fdb64cd4ec0836e9917c75f964dae (patch)
tree411d55759cf7c10d0772931614927994f5e24bab
parent0609ae5b62947b0d55505dec23b9b4d3a5909d89 (diff)
Fix tests to work without kubeconfig
-rw-r--r--robusta_krr/api/models.py6
-rw-r--r--robusta_krr/core/models/objects.py4
-rw-r--r--tests/conftest.py80
-rw-r--r--tests/test_krr.py22
4 files changed, 97 insertions, 15 deletions
diff --git a/robusta_krr/api/models.py b/robusta_krr/api/models.py
index be2a3ad..17a4487 100644
--- a/robusta_krr/api/models.py
+++ b/robusta_krr/api/models.py
@@ -1,6 +1,6 @@
-from robusta_krr.core.abstract.strategies import HistoryData, ResourceRecommendation, RunResult
+from robusta_krr.core.abstract.strategies import HistoryData, ResourceRecommendation, RunResult, ResourceHistoryData
from robusta_krr.core.models.allocations import RecommendationValue, ResourceAllocations, ResourceType
-from robusta_krr.core.models.objects import K8sObjectData
+from robusta_krr.core.models.objects import K8sObjectData, PodData
from robusta_krr.core.models.result import ResourceScan, Result, Severity
__all__ = [
@@ -8,10 +8,12 @@ __all__ = [
"ResourceAllocations",
"RecommendationValue",
"K8sObjectData",
+ "PodData",
"Result",
"Severity",
"ResourceScan",
"ResourceRecommendation",
"HistoryData",
+ "ResourceHistoryData",
"RunResult",
]
diff --git a/robusta_krr/core/models/objects.py b/robusta_krr/core/models/objects.py
index 21f5d61..29ce105 100644
--- a/robusta_krr/core/models/objects.py
+++ b/robusta_krr/core/models/objects.py
@@ -14,12 +14,12 @@ class PodData(pd.BaseModel):
class K8sObjectData(pd.BaseModel):
- cluster: Optional[str]
+ cluster: str
name: str
container: str
pods: list[PodData]
namespace: str
- kind: Optional[str]
+ kind: str
allocations: ResourceAllocations
def __str__(self) -> str:
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..ab9ca01
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,80 @@
+from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
+import pytest
+import numpy as np
+from datetime import datetime, timedelta
+import random
+from robusta_krr.api.models import K8sObjectData, PodData, ResourceAllocations, ResourceHistoryData
+
+
+TEST_OBJECT = K8sObjectData(
+ cluster="mock-cluster",
+ name="mock-object-1",
+ container="mock-container-1",
+ pods=[
+ PodData(name="mock-pod-1", deleted=False),
+ PodData(name="mock-pod-2", deleted=False),
+ PodData(name="mock-pod-3", deleted=True),
+ ],
+ namespace="default",
+ kind="Deployment",
+ allocations=ResourceAllocations(
+ requests={"cpu": 1, "memory": 1}, # type: ignore
+ limits={"cpu": 2, "memory": 2}, # type: ignore
+ ),
+)
+
+
+@pytest.fixture(autouse=True, scope="session")
+def mock_list_clusters():
+ with patch(
+ "robusta_krr.core.integrations.kubernetes.KubernetesLoader.list_clusters",
+ new=AsyncMock(return_value=[TEST_OBJECT.cluster]),
+ ):
+ yield
+
+
+@pytest.fixture(autouse=True, scope="session")
+def mock_list_scannable_objects():
+ with patch(
+ "robusta_krr.core.integrations.kubernetes.KubernetesLoader.list_scannable_objects",
+ new=AsyncMock(return_value=[TEST_OBJECT]),
+ ):
+ yield
+
+
+@pytest.fixture(autouse=True, scope="session")
+def mock_config_loaded():
+ with patch("robusta_krr.core.models.config.Config.config_loaded", new_callable=PropertyMock) as mock_config:
+ mock_config.return_value = True
+ yield
+
+
+@pytest.fixture(autouse=True, scope="session")
+def mock_prometheus_loader():
+ now = datetime.now()
+ start = now - timedelta(hours=1)
+ now_ts, start_ts = now.timestamp(), start.timestamp()
+ metric_points_data = np.array([(t, random.randrange(0, 100)) for t in np.linspace(start_ts, now_ts, 3600)])
+
+ with patch(
+ "robusta_krr.core.integrations.prometheus.loader.PrometheusLoader.gather_data",
+ new=AsyncMock(
+ return_value=ResourceHistoryData(
+ data={pod.name: metric_points_data for pod in TEST_OBJECT.pods},
+ metric={ # type: ignore
+ "query": f"example_promql_metric{{pod_name=~\"{'|'.join(pod.name for pod in TEST_OBJECT.pods)}\"}}",
+ "start_time": start,
+ "end_time": now,
+ "step": "30s",
+ },
+ )
+ ),
+ ) as mock_prometheus_loader:
+ mock_prometheus_loader
+ yield
+
+
+@pytest.fixture(autouse=True, scope="session")
+def mock_prometheus_init():
+ with patch("robusta_krr.core.integrations.prometheus.loader.PrometheusLoader.__init__", return_value=None):
+ yield
diff --git a/tests/test_krr.py b/tests/test_krr.py
index 23dab01..f013ee4 100644
--- a/tests/test_krr.py
+++ b/tests/test_krr.py
@@ -1,8 +1,3 @@
-"""
- Test the krr command line interface and a general execution.
- Requires a running kubernetes cluster with the kubectl command configured.
-"""
-
import json
import pytest
@@ -36,14 +31,19 @@ def test_run(log_flag: str):
@pytest.mark.parametrize("format", ["json", "yaml", "table", "pprint"])
def test_output_formats(format: str):
- result = runner.invoke(app, [STRATEGY_NAME, "-q", "-f", format, "--namespace", "default"])
+ result = runner.invoke(app, [STRATEGY_NAME, "-q", "-f", format])
try:
assert result.exit_code == 0, result.exc_info
except AssertionError as e:
raise e from result.exception
- if format == "json":
- assert json.loads(result.stdout), result.stdout
-
- if format == "yaml":
- assert yaml.safe_load(result.stdout), result.stdout
+ try:
+ if format == "json":
+ json_output = json.loads(result.stdout)
+ assert json_output, result.stdout
+ assert len(json_output["scans"]) > 0, result.stdout
+
+ if format == "yaml":
+ assert yaml.safe_load(result.stdout), result.stdout
+ except Exception as e:
+ raise Exception(result.stdout) from e