Refactor test cases for improved readability and consistency
Some checks failed
Run Tests / e2e tests (push) Failing after 1m27s
Run Tests / lint tests (push) Failing after 6s
Run Tests / unit tests (push) Failing after 7s

- Updated test functions in various test files to enhance code clarity by formatting long lines and improving indentation.
- Adjusted assertions to use multi-line formatting for better readability.
- Added new test cases for theme settings API to ensure proper functionality.
- Ensured consistent use of line breaks and spacing across test files for uniformity.
This commit is contained in:
2025-10-27 10:32:55 +01:00
parent e8a86b15e4
commit 97b1c0360b
78 changed files with 2327 additions and 650 deletions

View File

@@ -53,7 +53,9 @@ router = APIRouter()
templates = Jinja2Templates(directory="templates")
def _context(request: Request, extra: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
def _context(
request: Request, extra: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
payload: Dict[str, Any] = {
"request": request,
"current_year": datetime.now(timezone.utc).year,
@@ -98,7 +100,9 @@ def _load_scenarios(db: Session) -> Dict[str, Any]:
def _load_parameters(db: Session) -> Dict[str, Any]:
grouped: defaultdict[int, list[Dict[str, Any]]] = defaultdict(list)
for param in db.query(Parameter).order_by(Parameter.scenario_id, Parameter.id):
for param in db.query(Parameter).order_by(
Parameter.scenario_id, Parameter.id
):
grouped[param.scenario_id].append(
{
"id": param.id,
@@ -113,27 +117,20 @@ def _load_parameters(db: Session) -> Dict[str, Any]:
def _load_costs(db: Session) -> Dict[str, Any]:
capex_grouped: defaultdict[int, list[Dict[str, Any]]] = defaultdict(list)
for capex in (
db.query(Capex)
.order_by(Capex.scenario_id, Capex.id)
.all()
):
for capex in db.query(Capex).order_by(Capex.scenario_id, Capex.id).all():
capex_grouped[int(getattr(capex, "scenario_id"))].append(
{
"id": int(getattr(capex, "id")),
"scenario_id": int(getattr(capex, "scenario_id")),
"amount": float(getattr(capex, "amount", 0.0)),
"description": getattr(capex, "description", "") or "",
"currency_code": getattr(capex, "currency_code", "USD") or "USD",
"currency_code": getattr(capex, "currency_code", "USD")
or "USD",
}
)
opex_grouped: defaultdict[int, list[Dict[str, Any]]] = defaultdict(list)
for opex in (
db.query(Opex)
.order_by(Opex.scenario_id, Opex.id)
.all()
):
for opex in db.query(Opex).order_by(Opex.scenario_id, Opex.id).all():
opex_grouped[int(getattr(opex, "scenario_id"))].append(
{
"id": int(getattr(opex, "id")),
@@ -152,9 +149,15 @@ def _load_costs(db: Session) -> Dict[str, Any]:
def _load_currencies(db: Session) -> Dict[str, Any]:
items: list[Dict[str, Any]] = []
for c in db.query(Currency).filter_by(is_active=True).order_by(Currency.code).all():
for c in (
db.query(Currency)
.filter_by(is_active=True)
.order_by(Currency.code)
.all()
):
items.append(
{"id": c.code, "name": f"{c.name} ({c.code})", "symbol": c.symbol})
{"id": c.code, "name": f"{c.name} ({c.code})", "symbol": c.symbol}
)
if not items:
items.append({"id": "USD", "name": "US Dollar (USD)", "symbol": "$"})
return {"currency_options": items}
@@ -261,9 +264,7 @@ def _load_production(db: Session) -> Dict[str, Any]:
def _load_equipment(db: Session) -> Dict[str, Any]:
grouped: defaultdict[int, list[Dict[str, Any]]] = defaultdict(list)
for record in (
db.query(Equipment)
.order_by(Equipment.scenario_id, Equipment.id)
.all()
db.query(Equipment).order_by(Equipment.scenario_id, Equipment.id).all()
):
record_id = int(getattr(record, "id"))
scenario_id = int(getattr(record, "scenario_id"))
@@ -291,8 +292,9 @@ def _load_maintenance(db: Session) -> Dict[str, Any]:
scenario_id = int(getattr(record, "scenario_id"))
equipment_id = int(getattr(record, "equipment_id"))
equipment_obj = getattr(record, "equipment", None)
equipment_name = getattr(
equipment_obj, "name", "") if equipment_obj else ""
equipment_name = (
getattr(equipment_obj, "name", "") if equipment_obj else ""
)
maintenance_date = getattr(record, "maintenance_date", None)
cost_value = float(getattr(record, "cost", 0.0))
description = getattr(record, "description", "") or ""
@@ -303,7 +305,9 @@ def _load_maintenance(db: Session) -> Dict[str, Any]:
"scenario_id": scenario_id,
"equipment_id": equipment_id,
"equipment_name": equipment_name,
"maintenance_date": maintenance_date.isoformat() if maintenance_date else "",
"maintenance_date": (
maintenance_date.isoformat() if maintenance_date else ""
),
"cost": cost_value,
"description": description,
}
@@ -339,8 +343,11 @@ def _load_simulations(db: Session) -> Dict[str, Any]:
for item in scenarios:
scenario_id = int(item["id"])
scenario_results = results_grouped.get(scenario_id, [])
summary = generate_report(
scenario_results) if scenario_results else generate_report([])
summary = (
generate_report(scenario_results)
if scenario_results
else generate_report([])
)
runs.append(
{
"scenario_id": scenario_id,
@@ -395,11 +402,11 @@ def _load_dashboard(db: Session) -> Dict[str, Any]:
simulation_context = _load_simulations(db)
simulation_runs = simulation_context["simulation_runs"]
runs_by_scenario = {
run["scenario_id"]: run for run in simulation_runs
}
runs_by_scenario = {run["scenario_id"]: run for run in simulation_runs}
def sum_amounts(grouped: Dict[int, list[Dict[str, Any]]], field: str = "amount") -> float:
def sum_amounts(
grouped: Dict[int, list[Dict[str, Any]]], field: str = "amount"
) -> float:
total = 0.0
for items in grouped.values():
for item in items:
@@ -414,14 +421,18 @@ def _load_dashboard(db: Session) -> Dict[str, Any]:
total_production = sum_amounts(production_by_scenario)
total_maintenance_cost = sum_amounts(maintenance_by_scenario, field="cost")
total_parameters = sum(len(items)
for items in parameters_by_scenario.values())
total_equipment = sum(len(items)
for items in equipment_by_scenario.values())
total_maintenance_events = sum(len(items)
for items in maintenance_by_scenario.values())
total_parameters = sum(
len(items) for items in parameters_by_scenario.values()
)
total_equipment = sum(
len(items) for items in equipment_by_scenario.values()
)
total_maintenance_events = sum(
len(items) for items in maintenance_by_scenario.values()
)
total_simulation_iterations = sum(
run["iterations"] for run in simulation_runs)
run["iterations"] for run in simulation_runs
)
scenario_rows: list[Dict[str, Any]] = []
scenario_labels: list[str] = []
@@ -501,20 +512,40 @@ def _load_dashboard(db: Session) -> Dict[str, Any]:
overall_report = generate_report(all_simulation_results)
overall_report_metrics = [
{"label": "Runs", "value": _format_int(
int(overall_report.get("count", 0)))},
{"label": "Mean", "value": _format_decimal(
float(overall_report.get("mean", 0.0)))},
{"label": "Median", "value": _format_decimal(
float(overall_report.get("median", 0.0)))},
{"label": "Std Dev", "value": _format_decimal(
float(overall_report.get("std_dev", 0.0)))},
{"label": "95th Percentile", "value": _format_decimal(
float(overall_report.get("percentile_95", 0.0)))},
{"label": "VaR (95%)", "value": _format_decimal(
float(overall_report.get("value_at_risk_95", 0.0)))},
{"label": "Expected Shortfall (95%)", "value": _format_decimal(
float(overall_report.get("expected_shortfall_95", 0.0)))},
{
"label": "Runs",
"value": _format_int(int(overall_report.get("count", 0))),
},
{
"label": "Mean",
"value": _format_decimal(float(overall_report.get("mean", 0.0))),
},
{
"label": "Median",
"value": _format_decimal(float(overall_report.get("median", 0.0))),
},
{
"label": "Std Dev",
"value": _format_decimal(float(overall_report.get("std_dev", 0.0))),
},
{
"label": "95th Percentile",
"value": _format_decimal(
float(overall_report.get("percentile_95", 0.0))
),
},
{
"label": "VaR (95%)",
"value": _format_decimal(
float(overall_report.get("value_at_risk_95", 0.0))
),
},
{
"label": "Expected Shortfall (95%)",
"value": _format_decimal(
float(overall_report.get("expected_shortfall_95", 0.0))
),
},
]
recent_simulations: list[Dict[str, Any]] = [
@@ -522,8 +553,12 @@ def _load_dashboard(db: Session) -> Dict[str, Any]:
"scenario_name": run["scenario_name"],
"iterations": run["iterations"],
"iterations_display": _format_int(run["iterations"]),
"mean_display": _format_decimal(float(run["summary"].get("mean", 0.0))),
"p95_display": _format_decimal(float(run["summary"].get("percentile_95", 0.0))),
"mean_display": _format_decimal(
float(run["summary"].get("mean", 0.0))
),
"p95_display": _format_decimal(
float(run["summary"].get("percentile_95", 0.0))
),
}
for run in simulation_runs
if run["iterations"] > 0
@@ -541,10 +576,20 @@ def _load_dashboard(db: Session) -> Dict[str, Any]:
maintenance_date = getattr(record, "maintenance_date", None)
upcoming_maintenance.append(
{
"scenario_name": getattr(getattr(record, "scenario", None), "name", "Unknown"),
"equipment_name": getattr(getattr(record, "equipment", None), "name", "Unknown"),
"date_display": maintenance_date.strftime("%Y-%m-%d") if maintenance_date else "",
"cost_display": _format_currency(float(getattr(record, "cost", 0.0))),
"scenario_name": getattr(
getattr(record, "scenario", None), "name", "Unknown"
),
"equipment_name": getattr(
getattr(record, "equipment", None), "name", "Unknown"
),
"date_display": (
maintenance_date.strftime("%Y-%m-%d")
if maintenance_date
else ""
),
"cost_display": _format_currency(
float(getattr(record, "cost", 0.0))
),
"description": getattr(record, "description", "") or "",
}
)
@@ -552,9 +597,9 @@ def _load_dashboard(db: Session) -> Dict[str, Any]:
cost_chart_has_data = any(value > 0 for value in scenario_capex) or any(
value > 0 for value in scenario_opex
)
activity_chart_has_data = any(value > 0 for value in activity_production) or any(
value > 0 for value in activity_consumption
)
activity_chart_has_data = any(
value > 0 for value in activity_production
) or any(value > 0 for value in activity_consumption)
scenario_cost_chart: Dict[str, list[Any]] = {
"labels": scenario_labels,
@@ -573,14 +618,20 @@ def _load_dashboard(db: Session) -> Dict[str, Any]:
{"label": "CAPEX Total", "value": _format_currency(total_capex)},
{"label": "OPEX Total", "value": _format_currency(total_opex)},
{"label": "Equipment Assets", "value": _format_int(total_equipment)},
{"label": "Maintenance Events",
"value": _format_int(total_maintenance_events)},
{
"label": "Maintenance Events",
"value": _format_int(total_maintenance_events),
},
{"label": "Consumption", "value": _format_decimal(total_consumption)},
{"label": "Production", "value": _format_decimal(total_production)},
{"label": "Simulation Iterations",
"value": _format_int(total_simulation_iterations)},
{"label": "Maintenance Cost",
"value": _format_currency(total_maintenance_cost)},
{
"label": "Simulation Iterations",
"value": _format_int(total_simulation_iterations),
},
{
"label": "Maintenance Cost",
"value": _format_currency(total_maintenance_cost),
},
]
return {
@@ -704,3 +755,30 @@ async def currencies_view(request: Request, db: Session = Depends(get_db)):
"""Render the currency administration page with full currency context."""
context = _load_currency_settings(db)
return _render(request, "currencies.html", context)
@router.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
return _render(request, "login.html")
@router.get("/register", response_class=HTMLResponse)
async def register_page(request: Request):
return _render(request, "register.html")
@router.get("/profile", response_class=HTMLResponse)
async def profile_page(request: Request):
return _render(request, "profile.html")
@router.get("/forgot-password", response_class=HTMLResponse)
async def forgot_password_page(request: Request):
return _render(request, "forgot_password.html")
@router.get("/theme-settings", response_class=HTMLResponse)
async def theme_settings_page(request: Request, db: Session = Depends(get_db)):
"""Render the theme settings page."""
context = _load_css_settings(db)
return _render(request, "theme_settings.html", context)