Refactor code for consistency and readability
Some checks failed
CI / ci (push) Failing after 14s

- Standardized string quotes across multiple files to use double quotes for consistency.
- Improved formatting of JSON dumps in mock data for better readability.
- Enhanced the structure of various functions and data definitions for clarity.
- Updated test cases to reflect changes in data structure and ensure accuracy.
This commit is contained in:
2026-02-07 18:01:49 +03:00
parent 02b38a25eb
commit 2a0e0c216a
19 changed files with 322 additions and 209 deletions

View File

@@ -1,4 +1,5 @@
"""Tests for dashboard.openstack_utils.audits."""
from unittest.mock import MagicMock, patch
from django.test import TestCase
@@ -31,8 +32,10 @@ class ConvertCpuDataTest(TestCase):
self.assertEqual(len(hosts), 2)
self.assertIn("compute-0", hosts)
self.assertIn("compute-1", hosts)
# compute-0: (10+20)/2 for ts 1000 and 5 for ts 1000 -> groupby host,timestamp sum -> then groupby host mean
# For compute-0: two timestamps 1000 (10+5=15) and 1001 (20). Mean over timestamps = (15+20)/2 = 17.5
# compute-0: (10+20)/2 for ts 1000 and 5 for ts 1000 -> groupby host,timestamp sum
# -> then groupby host mean
# For compute-0: two timestamps 1000 (10+5=15) and 1001 (20).
# Mean over timestamps = (15+20)/2 = 17.5
# For compute-1: one value 30
by_host = result.set_index("host")["cpu_usage"]
self.assertAlmostEqual(by_host["compute-0"], 17.5)
@@ -60,11 +63,14 @@ class GetCurrentClusterCpuTest(TestCase):
@patch("dashboard.openstack_utils.audits.query_prometheus")
def test_returns_host_labels_and_cpu_current(self, mock_query, mock_convert):
import pandas as pd
mock_query.return_value = [{"metric": {"host": "h0"}, "values": [[0, "1.0"]]}]
mock_convert.return_value = pd.DataFrame({
"host": ["compute-0", "compute-1"],
"cpu_usage": [25.0, 35.0],
})
mock_convert.return_value = pd.DataFrame(
{
"host": ["compute-0", "compute-1"],
"cpu_usage": [25.0, 35.0],
}
)
conn = MagicMock()
result = get_current_cluster_cpu(conn)
self.assertEqual(result["host_labels"], ["compute-0", "compute-1"])

View File

@@ -1,4 +1,5 @@
"""Tests for dashboard.openstack_utils.flavor."""
from unittest.mock import MagicMock
from django.test import TestCase

View File

@@ -1,8 +1,9 @@
"""Tests for dashboard.templatetags.mathfilters."""
from django.test import TestCase
from django.template import Template, Context
from dashboard.templatetags.mathfilters import div, mul, sub, convert_bytes
from django.template import Context, Template
from django.test import TestCase
from dashboard.templatetags.mathfilters import convert_bytes, div, mul, sub
class DivFilterTest(TestCase):
@@ -48,25 +49,25 @@ class SubFilterTest(TestCase):
class ConvertBytesFilterTest(TestCase):
"""Tests for the convert_bytes template filter."""
def test_convert_to_B(self):
def test_convert_to_b(self):
self.assertEqual(convert_bytes(1024, "B"), 1024.0)
def test_convert_to_KB(self):
def test_convert_to_kb(self):
self.assertEqual(convert_bytes(2048, "KB"), 2.0)
def test_convert_to_MB(self):
def test_convert_to_mb(self):
self.assertEqual(convert_bytes(1024 * 1024 * 3, "MB"), 3.0)
def test_convert_to_GB(self):
self.assertEqual(convert_bytes(1024 ** 3 * 5, "GB"), 5.0)
def test_convert_to_gb(self):
self.assertEqual(convert_bytes(1024**3 * 5, "GB"), 5.0)
def test_convert_to_TB(self):
self.assertEqual(convert_bytes(1024 ** 4, "TB"), 1.0)
def test_convert_to_tb(self):
self.assertEqual(convert_bytes(1024**4, "TB"), 1.0)
def test_convert_default_GB(self):
self.assertEqual(convert_bytes(1024 ** 3 * 2), 2.0)
def test_convert_default_gb(self):
self.assertEqual(convert_bytes(1024**3 * 2), 2.0)
def test_convert_invalid_unit_fallback_to_MB(self):
def test_convert_invalid_unit_fallback_to_mb(self):
self.assertEqual(convert_bytes(1024 * 1024, "invalid"), 1.0)
self.assertEqual(convert_bytes(1024 * 1024, "xyz"), 1.0)
@@ -79,8 +80,8 @@ class ConvertBytesFilterTest(TestCase):
self.assertEqual(convert_bytes(1536 * 1024 * 1024, "GB"), 1.5)
def test_convert_case_insensitive_unit(self):
self.assertEqual(convert_bytes(1024 ** 3, "gb"), 1.0)
self.assertEqual(convert_bytes(1024 ** 3, "GB"), 1.0)
self.assertEqual(convert_bytes(1024**3, "gb"), 1.0)
self.assertEqual(convert_bytes(1024**3, "GB"), 1.0)
class MathfiltersTemplateIntegrationTest(TestCase):
@@ -100,4 +101,4 @@ class MathfiltersTemplateIntegrationTest(TestCase):
def test_convert_bytes_in_template(self):
t = Template("{% load mathfilters %}{{ bytes|convert_bytes:'GB' }}")
self.assertEqual(t.render(Context({"bytes": 1024 ** 3 * 2})), "2.0")
self.assertEqual(t.render(Context({"bytes": 1024**3 * 2})), "2.0")

View File

@@ -1,4 +1,5 @@
"""Tests for dashboard.mock_data."""
import json
from django.test import TestCase
@@ -11,7 +12,17 @@ class GetMockContextTest(TestCase):
def test_returns_all_top_level_keys(self):
ctx = get_mock_context()
expected_keys = {"region", "pcpu", "vcpu", "pram", "vram", "vm", "flavors", "audits", "current_cluster"}
expected_keys = {
"region",
"pcpu",
"vcpu",
"pram",
"vram",
"vm",
"flavors",
"audits",
"current_cluster",
}
self.assertEqual(set(ctx.keys()), expected_keys)
def test_region_structure(self):

View File

@@ -1,5 +1,6 @@
"""Tests for dashboard.prometheus_utils.query."""
from unittest.mock import patch, MagicMock
from unittest.mock import MagicMock, patch
from django.test import TestCase
@@ -12,13 +13,7 @@ class QueryPrometheusTest(TestCase):
@patch("dashboard.prometheus_utils.query.requests.get")
def test_single_result_returns_value_string(self, mock_get):
mock_response = MagicMock()
mock_response.json.return_value = {
"data": {
"result": [
{"value": ["1234567890", "42"]}
]
}
}
mock_response.json.return_value = {"data": {"result": [{"value": ["1234567890", "42"]}]}}
mock_response.raise_for_status = MagicMock()
mock_get.return_value = mock_response

View File

@@ -1,18 +1,17 @@
"""Tests for dashboard.views."""
import json
from unittest.mock import patch, MagicMock
from django.test import TestCase, RequestFactory
import json
from unittest.mock import MagicMock, patch
from django.core.cache import cache
from django.test import RequestFactory, TestCase
from dashboard.views import (
index,
collect_context,
collect_stats,
collect_audits,
api_stats,
api_audits,
api_source_status,
api_stats,
collect_context,
index,
)
@@ -21,10 +20,31 @@ def _minimal_render_context(region_name="test", first_flavor_name="f1", vm_count
return {
"region": {"name": region_name, "hosts_total": 1},
"pcpu": {"total": 1, "usage": 0, "free": 1, "used_percentage": 0},
"vcpu": {"total": 2, "allocated": 1, "free": 1, "allocated_percentage": 50, "overcommit_ratio": 1, "overcommit_max": 2},
"vcpu": {
"total": 2,
"allocated": 1,
"free": 1,
"allocated_percentage": 50,
"overcommit_ratio": 1,
"overcommit_max": 2,
},
"pram": {"total": 1024**3, "usage": 0, "free": 1024**3, "used_percentage": 0},
"vram": {"total": 1024**3, "allocated": 0, "free": 1024**3, "allocated_percentage": 0, "overcommit_ratio": 0, "overcommit_max": 1},
"vm": {"count": vm_count, "active": vm_count, "stopped": 0, "avg_cpu": 1, "avg_ram": 0, "density": float(vm_count)},
"vram": {
"total": 1024**3,
"allocated": 0,
"free": 1024**3,
"allocated_percentage": 0,
"overcommit_ratio": 0,
"overcommit_max": 1,
},
"vm": {
"count": vm_count,
"active": vm_count,
"stopped": 0,
"avg_cpu": 1,
"avg_ram": 0,
"density": float(vm_count),
},
"flavors": {
"first_common_flavor": {"name": first_flavor_name, "count": vm_count},
"second_common_flavor": {"name": "", "count": 0},
@@ -81,10 +101,18 @@ class CollectContextTest(TestCase):
@patch("dashboard.views.get_flavor_list")
@patch("dashboard.views.get_connection")
def test_collect_context_structure_and_calculation(
self, mock_get_connection, mock_get_flavor_list, mock_get_audits, mock_fetch_metrics, mock_get_current_cluster_cpu
self,
mock_get_connection,
mock_get_flavor_list,
mock_get_audits,
mock_fetch_metrics,
mock_get_current_cluster_cpu,
):
mock_get_connection.return_value = self._make_mock_connection("my-region")
mock_get_current_cluster_cpu.return_value = {"host_labels": ["h0", "h1"], "cpu_current": [30.0, 40.0]}
mock_get_current_cluster_cpu.return_value = {
"host_labels": ["h0", "h1"],
"cpu_current": [30.0, 40.0],
}
mock_get_flavor_list.return_value = {
"first_common_flavor": {"name": "m1.small", "count": 5},
"second_common_flavor": {"name": "", "count": 0},
@@ -125,6 +153,7 @@ class CollectContextTest(TestCase):
self.assertEqual(len(context["audits"]), 1)
# Serialized for JS
import json
self.assertIsInstance(context["audits"][0]["migrations"], str)
self.assertEqual(json.loads(context["audits"][0]["host_labels"]), ["h0", "h1"])
self.assertIn("current_cluster", context)
@@ -187,7 +216,15 @@ class ApiStatsTest(TestCase):
@patch("dashboard.views.settings")
def test_api_stats_uses_cache(self, mock_settings, mock_collect_stats):
mock_settings.DASHBOARD_CACHE_TTL = 120
cached = {"region": {"name": "cached", "hosts_total": 1}, "pcpu": {}, "pram": {}, "vcpu": {}, "vram": {}, "vm": {}, "flavors": {}}
cached = {
"region": {"name": "cached", "hosts_total": 1},
"pcpu": {},
"pram": {},
"vcpu": {},
"vram": {},
"vm": {},
"flavors": {},
}
cache.clear()
cache.set("dashboard_stats", cached, timeout=120)
request = self.factory.get("/api/stats/")
@@ -219,13 +256,24 @@ class ApiAuditsTest(TestCase):
"scope": "Full Cluster",
"cpu_weight": "1.0",
"ram_weight": "1.0",
"migrations": [{"instanceName": "i1", "source": "h0", "destination": "h1", "flavor": "m1.small", "impact": "Low"}],
"migrations": [
{
"instanceName": "i1",
"source": "h0",
"destination": "h1",
"flavor": "m1.small",
"impact": "Low",
}
],
"host_labels": ["h0", "h1"],
"cpu_current": [30.0, 40.0],
"cpu_projected": [35.0, 35.0],
}
]
mock_get_current_cluster_cpu.return_value = {"host_labels": ["h0", "h1"], "cpu_current": [30.0, 40.0]}
mock_get_current_cluster_cpu.return_value = {
"host_labels": ["h0", "h1"],
"cpu_current": [30.0, 40.0],
}
cache.clear()
request = self.factory.get("/api/audits/")
with patch("dashboard.views.settings") as mock_settings:
@@ -246,9 +294,20 @@ class ApiAuditsTest(TestCase):
@patch("dashboard.views.get_current_cluster_cpu")
@patch("dashboard.views.collect_audits")
@patch("dashboard.views.settings")
def test_api_audits_uses_cache(self, mock_settings, mock_collect_audits, mock_get_current_cluster_cpu):
def test_api_audits_uses_cache(
self, mock_settings, mock_collect_audits, mock_get_current_cluster_cpu
):
mock_settings.DASHBOARD_CACHE_TTL = 120
cached_audits = [{"id": "cached-1", "name": "Cached Audit", "migrations": "[]", "host_labels": "[]", "cpu_current": "[]", "cpu_projected": "[]"}]
cached_audits = [
{
"id": "cached-1",
"name": "Cached Audit",
"migrations": "[]",
"host_labels": "[]",
"cpu_current": "[]",
"cpu_projected": "[]",
}
]
cached_cluster = {"host_labels": ["cached-h0"], "cpu_current": [10.0]}
cache.clear()
cache.set("dashboard_audits", cached_audits, timeout=120)