Files
Homelab-manager/server/test/electricity.test.ts
T
bobbanandClaude Sonnet 5.5 f546971000 Add an electricity estimate to the Costs page
The typical draws in the Inventory, the price of a kWh and the currency set
there give a cost per device and in all, counted in the totals under an
Electricity category when there is a draw, a price and a three-letter currency,
and said plainly (with what is missing) when there is not.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 20:59:50 +01:00

145 lines
8.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* The electricity estimate under Costs: the typical draws in the Inventory, the price of a kWh and the currency set there give a cost per device and in all, counted in the totals when there is a draw,
* a price and a three-letter currency — and said plainly, with what is missing, when there is not.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-electricity-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, assets, costSnapshots } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const costs = await import("../src/services/costs.js");
const history = await import("../src/services/costHistory.js");
const { costsRouter } = await import("../src/routes/costs.js");
const { updateSettings } = await import("../src/services/settingsStore.js");
await runMigrations();
const hw = (id: number, name: string, watts: number | null, kind = "server") => ({ id, name, kind, powerWatts: watts });
describe("the estimate", () => {
test("a steady draw over an average month at the price: watts × 730 hours, in kWh, times the price", () => {
assert.equal(Math.round(costs.HOURS_PER_MONTH), 730);
const e = costs.electricityEstimate([hw(1, "nas", 50)], { pricePerKwh: 2, currency: "SEK" });
// 50 W × 730 h = 36.5 kWh; × 2 = 73.00
assert.deepEqual([e.watts, e.kwhPerMonth, e.monthly, e.yearly, e.currency, e.includedInTotals, e.missing], [50, 36.5, 73, 876, "SEK", true, null]);
});
test("each device has its own cost and its share, the biggest first, and what is left out is counted", () => {
const e = costs.electricityEstimate([hw(1, "switch", 20, "network"), hw(2, "pve1", 150), hw(3, "ups", null, "power"), hw(4, "pi", 5), hw(5, "off", 0)], { pricePerKwh: 1.5, currency: "eur" });
assert.deepEqual(e.devices.map((d) => [d.name, d.watts, d.share]), [["pve1", 150, 85.7], ["switch", 20, 11.4], ["pi", 5, 2.9]]);
assert.equal(e.watts, 175);
assert.equal(e.withoutDraw, 2, "a missing draw and a draw of nothing are both without one");
assert.equal(e.devices[0].monthly, Math.round(0.15 * 730 * 1.5 * 100) / 100);
assert.equal(e.currency, "EUR", "a code is made capitals");
});
test("devices with the same draw come by name", () => {
const e = costs.electricityEstimate([hw(1, "b", 10), hw(2, "a", 10)], { pricePerKwh: 1, currency: "SEK" });
assert.deepEqual(e.devices.map((d) => d.name), ["a", "b"]);
});
test("without a draw there is nothing to say; without a price there is the draw but no cost; with a currency that is not a code it is worked out but not counted", () => {
const none = costs.electricityEstimate([hw(1, "x", null)], { pricePerKwh: 2, currency: "SEK" });
assert.deepEqual([none.watts, none.monthly, none.includedInTotals, none.missing], [0, null, false, "draw"]);
const noPrice = costs.electricityEstimate([hw(1, "x", 100)], { pricePerKwh: null, currency: "SEK" });
assert.deepEqual([noPrice.watts, noPrice.monthly, noPrice.devices[0].monthly, noPrice.missing, noPrice.includedInTotals], [100, null, null, "price", false]);
const kr = costs.electricityEstimate([hw(1, "x", 100)], { pricePerKwh: 2, currency: "kr" });
assert.deepEqual([kr.monthly, kr.currency, kr.currencyLabel, kr.missing, kr.includedInTotals], [146, null, "kr", "currency", false]);
for (const bad of ["", "SE", "SEKK", "€", "12"]) assert.equal(costs.electricityEstimate([hw(1, "x", 100)], { pricePerKwh: 2, currency: bad }).currency, null, JSON.stringify(bad));
});
test("a price of zero or less is no price", () => {
for (const price of [0, -1, null]) assert.equal(costs.electricityEstimate([hw(1, "x", 100)], { pricePerKwh: price, currency: "SEK" }).monthly, null);
});
});
describe("in the totals", () => {
test("a read estimate is filed under its own category, and Hosting when it says none", () => {
const t = costs.costTotals([], [{ currency: "SEK", monthly: 100, category: "Electricity" }, { currency: "SEK", monthly: 50 }]);
assert.deepEqual(t[0].categories, [{ category: "Electricity", monthly: 100 }, { category: "Hosting", monthly: 50 }]);
});
});
describe("through the page's route", () => {
let app: Server;
let base = "";
before(async () => {
await db.insert(users).values({ oidcSub: "viewer", name: "Vic", role: "viewer" });
await db.insert(assets).values([
{ name: "pve1", kind: "server", powerWatts: 150, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },
{ name: "nas", kind: "storage", powerWatts: 50, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },
{ name: "shelf", kind: "other", powerWatts: null, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },
]);
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: "viewer" } };
next();
});
a.use("/api/costs", costsRouter);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/costs`;
});
after(async () => {
app.close();
await updateSettings({ inventory: { currency: "", pricePerKwh: null } });
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const report = async () => (await (await fetch(base)).json()) as { electricity: Awaited<ReturnType<typeof costs.currentElectricity>>; automatic: { key: string; monthly: number; category?: string; currency: string; link: string }[]; totals: { currency: string; monthly: number; categories: { category: string; monthly: number }[] }[] };
test("with draws but no price it says what is missing, shows the draw, and adds nothing to the totals", async () => {
await updateSettings({ inventory: { currency: "SEK", pricePerKwh: null } });
const r = await report();
assert.deepEqual([r.electricity.watts, r.electricity.missing, r.electricity.includedInTotals, r.electricity.monthly], [200, "price", false, null]);
assert.equal(r.automatic.some((a) => a.key === "electricity"), false);
assert.deepEqual(r.totals, []);
});
test("with a price and a three-letter currency it is counted in the totals, under Electricity, and anyone signed in sees it", async () => {
await updateSettings({ inventory: { currency: "SEK", pricePerKwh: 2 } });
const r = await report();
// 200 W × 730 h = 146 kWh × 2 = 292
assert.deepEqual([r.electricity.monthly, r.electricity.yearly, r.electricity.includedInTotals], [292, 3504, true]);
assert.deepEqual(r.electricity.devices.map((d) => d.name), ["pve1", "nas"]);
const auto = r.automatic.find((a) => a.key === "electricity")!;
assert.deepEqual([auto.monthly, auto.currency, auto.category, auto.link], [292, "SEK", "Electricity", "/inventory"]);
assert.deepEqual(r.totals.map((t) => [t.currency, t.monthly, t.categories]), [["SEK", 292, [{ category: "Electricity", monthly: 292 }]]]);
});
test("a currency that is not a code leaves it out of the totals but still works it out", async () => {
await updateSettings({ inventory: { currency: "kr", pricePerKwh: 2 } });
const r = await report();
assert.deepEqual([r.electricity.monthly, r.electricity.currency, r.electricity.includedInTotals, r.electricity.missing], [292, null, false, "currency"]);
assert.deepEqual(r.totals, []);
});
test("a change in the draws or the price is a new figure the next time it is read, and the daily snapshot keeps it for the history", async () => {
await updateSettings({ inventory: { currency: "SEK", pricePerKwh: 3 } });
assert.equal((await report()).electricity.monthly, 438);
await history.snapshotAutomatic(new Date("2026-11-10T12:00:00Z"));
const snaps = (await db.select().from(costSnapshots)).filter((s) => s.key === "electricity");
assert.deepEqual(snaps.map((s) => [s.day, s.currency, s.monthly]), [["2026-11-10", "SEK", 438]]);
});
});