Skip to content

armgit / dashy

Public Imported from GitHub
0

πŸš€ A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!

πŸ§ͺ️ Tests and docs working for uptime kuma widget

Alicia Sykesefa00000a7e8
diff --git a/docs/widgets.md b/docs/widgets.md
index a586b705..868c4990 100644
--- a/docs/widgets.md
+++ b/docs/widgets.md
@@ -2819,7 +2819,7 @@ Linkding is a self-hosted bookmarking service, which has a clean interface and i
#### Info
-- **CORS**: 🟒 Enabled
+- **CORS**: πŸ”΄ Proxied
- **Auth**: 🟒 Required
- **Price**: 🟒 Free
- **Host**: Self-Hosted (see [Uptime Kuma](https://github.com/louislam/uptime-kuma) )
diff --git a/src/components/Widgets/UptimeKuma.vue b/src/components/Widgets/UptimeKuma.vue
index 9faae0ea..c6695e27 100644
--- a/src/components/Widgets/UptimeKuma.vue
+++ b/src/components/Widgets/UptimeKuma.vue
@@ -1,15 +1,17 @@
<template>
<div>
<template v-if="monitors">
- <div v-for="(monitor, index) in monitors" :key="index" class="item-wrapper">
+ <div v-for="monitor in monitors" :key="monitor.name" class="item-wrapper">
<div class="item monitor-row">
<div class="title-title"><span class="text">{{ monitor.name }}</span></div>
<div class="monitors-container">
<div class="status-container">
- <span class="status-pill" :class="[monitor.statusClass]">{{ monitor.status }}</span>
+ <span class="status-pill" :class="getStatusClass(monitor.status)">
+ {{ getStatusText(monitor.status) }}
+ </span>
</div>
<div class="status-container">
- <span class="response-time">{{ monitor.responseTime }}ms</span>
+ <span class="response-time">{{ formatResponseTime(monitor.responseTime) }}</span>
</div>
</div>
</div>
@@ -26,15 +28,21 @@
<script>
/**
- * A simple example which you can use as a template for creating your own widget.
- * Takes two optional parameters (`text` and `count`), and fetches a list of images
- * from dummyapis.com, then renders the results to the UI.
+ * Renders the status and response time of each monitor on an Uptime Kuma
+ * instance, read from its Prometheus-format `/metrics` endpoint
*/
import WidgetMixin from '@/mixins/WidgetMixin';
+const STATUSES = {
+ 0: { text: 'Down', class: 'down' },
+ 1: { text: 'Up', class: 'up' },
+ 2: { text: 'Pending', class: 'pending' },
+ 3: { text: 'Maintenance', class: 'maintenance' },
+};
+const UNKNOWN = { text: 'Unknown', class: 'unknown' };
+
export default {
mixins: [WidgetMixin],
- components: {},
data() {
return {
monitors: null,
@@ -46,9 +54,6 @@ export default {
};
},
- mounted() {
- this.fetchData();
- },
computed: {
/* Get API key for access to instance */
apiKey() {
@@ -68,23 +73,34 @@ export default {
},
},
methods: {
- /* The update() method extends mixin, used to update the data.
- * It's called by parent component, when the user presses update
- */
+ getStatusText(status) {
+ return (STATUSES[status] || UNKNOWN).text;
+ },
+ getStatusClass(status) {
+ return (STATUSES[status] || UNKNOWN).class;
+ },
update() {
this.startLoading();
this.fetchData();
},
/* Make the data request to the computed API endpoint */
fetchData() {
- const { authHeaders, url } = this;
+ const { authHeaders, url, apiKey } = this;
- if (!this.optionsValid({ authHeaders, url })) {
+ if (!this.optionsValid({ url, apiKey })) {
return;
}
this.makeRequest(url, authHeaders)
- .then(this.processData);
+ .then(this.processData)
+ .catch((error) => {
+ this.errorMessage = error.message || 'Failed to fetch data';
+ });
+ },
+ /* Add ms unit to response time if it valid (-1 means no ping) */
+ formatResponseTime(responseTime) {
+ const ms = Number(responseTime);
+ return Number.isFinite(ms) && ms >= 0 ? `${ms}ms` : '-';
},
/* Convert API response data into a format to be consumed by the UI */
processData(response) {
@@ -97,15 +113,19 @@ export default {
this.processRow(row, monitors);
}
+ this.errorMessage = null;
this.monitors = Array.from(monitors.values());
},
getMonitorRows(response) {
+ if (typeof response !== 'string') return [];
return response.split('\n').filter(row => row.startsWith('monitor_'));
},
processRow(row, monitors) {
const dataType = this.getRowDataType(row);
const monitorName = this.getRowMonitorName(row);
+ if (!monitorName) return;
+
if (!monitors.has(monitorName)) {
monitors.set(monitorName, { name: monitorName });
}
@@ -133,8 +153,7 @@ export default {
break;
}
case 'monitor_status': {
- copy.status = value === '1' ? 'Up' : 'Down';
- copy.statusClass = copy.status.toLowerCase();
+ copy.status = Number(value);
break;
}
default:
@@ -144,7 +163,7 @@ export default {
return copy;
},
getRowValue(row) {
- return this.getValueWithRegex(row, /\b(\d+)(\.\d+)*\b$/);
+ return this.getValueWithRegex(row, /\s(\S+)\s*$/);
},
getRowMonitorName(row) {
return this.getValueWithRegex(row, /monitor_name="([^"]+)"/);
@@ -163,13 +182,13 @@ export default {
return result.length > 1 ? result[1] : result[0];
},
- optionsValid({ url, authHeaders }) {
+ optionsValid({ url, apiKey }) {
const errors = [];
- if (url === undefined) {
+ if (!url) {
errors.push(this.errorMessageConstants.missingUrl);
}
- if (authHeaders === undefined) {
+ if (!apiKey) {
errors.push(this.errorMessageConstants.missingApiKey);
}
@@ -192,7 +211,7 @@ export default {
text-align: center;
white-space: nowrap;
vertical-align: baseline;
- padding: .35em .65em;
+ padding: 0.35em 0.65em;
margin: 0.1em 0.5em;
min-width: 64px;
@@ -200,11 +219,22 @@ export default {
background-color: var(--success);
color: var(--black);
}
-
&.down {
background-color: var(--danger);
color: var(--white);
}
+ &.pending {
+ background-color: var(--warning);
+ color: var(--black);
+ }
+ &.maintenance {
+ background-color: var(--info);
+ color: var(--black);
+ }
+ &.unknown {
+ background-color: var(--neutral);
+ color: var(--white);
+ }
}
div.item.monitor-row:hover {
diff --git a/src/components/Widgets/UptimeKumaStatusPage.vue b/src/components/Widgets/UptimeKumaStatusPage.vue
index 5668daff..09893828 100644
--- a/src/components/Widgets/UptimeKumaStatusPage.vue
+++ b/src/components/Widgets/UptimeKumaStatusPage.vue
@@ -7,8 +7,8 @@
</template>
<template v-else-if="lastHeartbeats">
<div
- v-for="(heartbeat, index) in lastHeartbeats"
- :key="index"
+ v-for="heartbeat in lastHeartbeats"
+ :key="heartbeat.id"
class="item-wrapper"
>
<div class="item monitor-row">
@@ -34,6 +34,14 @@
<script>
import WidgetMixin from '@/mixins/WidgetMixin';
+const STATUSES = {
+ 0: { text: 'Down', class: 'down' },
+ 1: { text: 'Up', class: 'up' },
+ 2: { text: 'Pending', class: 'pending' },
+ 3: { text: 'Maintenance', class: 'maintenance' },
+};
+const UNKNOWN = { text: 'Unknown', class: 'unknown' };
+
export default {
mixins: [WidgetMixin],
data() {
@@ -59,7 +67,6 @@ export default {
endpoint() {
return `${this.host}/api/status-page/heartbeat/${this.slug}`;
},
- /* Monitor names aren't in the heartbeat response, they're only here */
configEndpoint() {
return `${this.host}/api/status-page/${this.slug}`;
},
@@ -67,10 +74,13 @@ export default {
return `${this.host}/status/${this.slug}`;
},
},
- mounted() {
- this.fetchData();
- },
methods: {
+ getStatusText(status) {
+ return (STATUSES[status] || UNKNOWN).text;
+ },
+ getStatusClass(status) {
+ return (STATUSES[status] || UNKNOWN).class;
+ },
update() {
this.startLoading();
this.fetchData();
@@ -91,16 +101,17 @@ export default {
},
processData(response, statusPage) {
const { heartbeatList } = response;
+ this.errorMessage = null;
this.lastHeartbeats = this.getOrderedMonitors(statusPage, heartbeatList)
.map((monitor, index) => {
const heartbeats = heartbeatList[monitor.id];
return {
...heartbeats[heartbeats.length - 1],
+ id: monitor.id,
name: this.monitorNames[index] || monitor.name || `Monitor ${index + 1}`,
};
});
},
- /* Monitors which have heartbeats, in the same order as the status page */
getOrderedMonitors(statusPage, heartbeatList) {
const groups = statusPage?.publicGroupList;
const monitors = groups
@@ -121,42 +132,11 @@ export default {
openStatusPage() {
window.open(this.statusPageUrl, '_blank');
},
- getStatusText(status) {
- switch (status) {
- case 1:
- return 'Up';
- case 0:
- return 'Down';
- case 2:
- return 'Pending';
- case 3:
- return 'Maintenance';
- default:
- return 'Unknown';
- }
- },
- getStatusClass(status) {
- switch (status) {
- case 1:
- return 'up';
- case 0:
- return 'down';
- case 2:
- return 'pending';
- case 3:
- return 'maintenance';
- default:
- return 'unknown';
- }
- },
},
};
</script>
<style scoped lang="scss">
-.clickable-widget {
- cursor: pointer;
-}
.status-pill {
border-radius: 50em;
box-sizing: border-box;
@@ -169,6 +149,7 @@ export default {
padding: 0.35em 0.65em;
margin: 0.1em 0.5em;
min-width: 64px;
+
&.up {
background-color: var(--success);
color: var(--black);
@@ -190,6 +171,10 @@ export default {
color: var(--white);
}
}
+
+.clickable-widget {
+ cursor: pointer;
+}
.monitor-row {
display: flex;
justify-content: space-between;
diff --git a/tests/components/widgets/uptimekuma.test.js b/tests/components/widgets/uptimekuma.test.js
new file mode 100644
index 00000000..5e3a8285
--- /dev/null
+++ b/tests/components/widgets/uptimekuma.test.js
@@ -0,0 +1,80 @@
+import {
+ describe, it, expect, beforeEach, vi,
+} from 'vitest';
+import { shallowMount, flushPromises } from '@vue/test-utils';
+import request from '@/utils/request';
+import UptimeKuma from '@/components/Widgets/UptimeKuma.vue';
+
+vi.mock('@/utils/request', () => ({ default: vi.fn() }));
+vi.mock('@/utils/logging/ErrorHandler', () => ({ default: vi.fn() }));
+
+/* Prometheus rows, as Uptime Kuma writes them on /metrics */
+const row = (metric, name, value) => `${metric}{monitor_id="1",monitor_name="${name}",`
+ + `monitor_type="http",monitor_url="https://example.com"} ${value}`;
+
+const metrics = [
+ '# HELP monitor_status Monitor Status (1 = UP, 0= DOWN, 2= PENDING, 3= MAINTENANCE)',
+ row('monitor_status', 'App', 1),
+ row('monitor_status', 'Docs', 2),
+ row('monitor_status', 'API', 3),
+ row('monitor_response_time', 'App', 83),
+ row('monitor_response_time', 'Docs', -1),
+ row('monitor_response_time', 'API', 112),
+].join('\n');
+
+async function mount(options = {}) {
+ const wrapper = shallowMount(UptimeKuma, {
+ props: {
+ options: {
+ useProxy: false,
+ url: 'https://uptime.example.com/metrics',
+ apiKey: 'uk1_test',
+ ...options,
+ },
+ },
+ });
+ await flushPromises();
+ return wrapper;
+}
+
+const textOf = (wrapper, selector) => wrapper.findAll(selector).map((n) => n.text());
+
+describe('UptimeKuma widget', () => {
+ beforeEach(() => {
+ request.mockReset();
+ request.mockResolvedValue({ data: metrics });
+ });
+
+ it('names each monitor, from its metric labels', async () => {
+ expect(textOf(await mount(), '.title-title')).toEqual(['App', 'Docs', 'API']);
+ });
+
+ it('distinguishes pending and maintenance from down', async () => {
+ const pills = (await mount()).findAll('.status-pill');
+ expect(pills.map((p) => p.text())).toEqual(['Up', 'Pending', 'Maintenance']);
+ expect(pills[1].classes()).toContain('pending');
+ });
+
+ it('shows a placeholder for a monitor with no ping, which Kuma reports as -1', async () => {
+ expect(textOf(await mount(), '.response-time')).toEqual(['83ms', '-', '112ms']);
+ });
+
+ it.each([
+ ['apiKey', 'No API key set'],
+ ['url', 'No URL set'],
+ ])('asks for a %s when one is missing', async (option, message) => {
+ const wrapper = await mount({ [option]: undefined });
+ expect(wrapper.find('.error-message').text()).toBe(message);
+ expect(request).not.toHaveBeenCalled();
+ });
+
+ it('shows a message when the request fails', async () => {
+ request.mockRejectedValue(new Error('Request failed with status code 401'));
+ expect((await mount()).find('.error-message').text()).toContain('401');
+ });
+
+ it('renders nothing when the response is not metrics text', async () => {
+ request.mockResolvedValue({ data: { unexpected: 'json' } });
+ expect((await mount()).findAll('.monitor-row')).toHaveLength(0);
+ });
+});
diff --git a/tests/components/widgets/uptimekumastatuspage.test.js b/tests/components/widgets/uptimekumastatuspage.test.js
new file mode 100644
index 00000000..116bd9ba
--- /dev/null
+++ b/tests/components/widgets/uptimekumastatuspage.test.js
@@ -0,0 +1,91 @@
+import {
+ describe, it, expect, beforeEach, vi,
+} from 'vitest';
+import { shallowMount, flushPromises } from '@vue/test-utils';
+import request from '@/utils/request';
+import UptimeKumaStatusPage from '@/components/Widgets/UptimeKumaStatusPage.vue';
+
+vi.mock('@/utils/request', () => ({ default: vi.fn() }));
+vi.mock('@/utils/logging/ErrorHandler', () => ({ default: vi.fn() }));
+
+/* Note the display order (App, API, Docs) differs from monitor id order (5, 6, 7) */
+const statusPage = {
+ publicGroupList: [
+ {
+ name: 'Web',
+ monitorList: [{ id: 5, name: 'App' }, { id: 7, name: 'API' }, { id: 6, name: 'Docs' }],
+ },
+ { name: 'Auth', monitorList: [] },
+ ],
+};
+
+const beats = (status) => [{ status: 1, ping: 91 }, { status, ping: 83 }];
+const heartbeats = { heartbeatList: { 5: beats(1), 7: beats(0), 6: beats(1) } };
+
+/* Heartbeats and monitor names come from two separate endpoints */
+function mockApi({ beatData = heartbeats, pageData = statusPage } = {}) {
+ request.mockImplementation(({ url }) => {
+ if (url.includes('/heartbeat/')) return Promise.resolve({ data: beatData });
+ if (!pageData) return Promise.reject(new Error('Status Page Not Found'));
+ return Promise.resolve({ data: pageData });
+ });
+}
+
+async function mount(options = {}) {
+ const wrapper = shallowMount(UptimeKumaStatusPage, {
+ props: {
+ options: {
+ useProxy: false, host: 'https://uptime.example.com', slug: 'domain-locker', ...options,
+ },
+ },
+ });
+ await flushPromises();
+ return wrapper;
+}
+
+const names = (wrapper) => wrapper.findAll('.title-title').map((n) => n.text());
+
+describe('UptimeKumaStatusPage widget', () => {
+ beforeEach(() => {
+ request.mockReset();
+ mockApi();
+ });
+
+ it('names each monitor, in the order the status page lists them', async () => {
+ expect(names(await mount())).toEqual(['App', 'API', 'Docs']);
+ });
+
+ it('shows each monitor status, from its latest heartbeat', async () => {
+ const pills = (await mount()).findAll('.status-pill');
+ expect(pills.map((p) => p.text())).toEqual(['Up', 'Down', 'Up']);
+ expect(pills[1].classes()).toContain('down');
+ });
+
+ it('lets monitorNames override the names from Uptime Kuma', async () => {
+ expect(names(await mount({ monitorNames: ['One', 'Two', 'Three'] }))).toEqual(['One', 'Two', 'Three']);
+ });
+
+ it('keeps the real name where monitorNames runs out', async () => {
+ expect(names(await mount({ monitorNames: ['One'] }))).toEqual(['One', 'API', 'Docs']);
+ });
+
+ it('ignores a monitorNames given as a string rather than a list', async () => {
+ expect(names(await mount({ monitorNames: '["One","Two"]' }))).toEqual(['App', 'API', 'Docs']);
+ });
+
+ it('numbers the monitors when the status page cannot be reached', async () => {
+ mockApi({ pageData: null });
+ expect(names(await mount())).toEqual(['Monitor 1', 'Monitor 2', 'Monitor 3']);
+ });
+
+ it('skips monitors with no heartbeats yet', async () => {
+ mockApi({ beatData: { heartbeatList: { 5: beats(1), 7: [], 6: beats(1) } } });
+ expect(names(await mount())).toEqual(['App', 'Docs']);
+ });
+
+ it('asks for a slug when one is missing', async () => {
+ const wrapper = await mount({ slug: undefined });
+ expect(wrapper.find('.error-message').text()).toBe('No slug set');
+ expect(request).not.toHaveBeenCalled();
+ });
+});