Skip to content

Commit 8fc77ed

Browse files
committed
Refactor how influx lib is tested
1 parent 81e8b56 commit 8fc77ed

File tree

4 files changed

+80
-74
lines changed

4 files changed

+80
-74
lines changed

bin/worker.js

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,9 @@
1-
import { reportRequestMetric } from "../lib/influx.js";
1+
import { reportRequestMetric } from '../lib/influx.js'
22

33
export default {
4-
async fetch(request, env, ctx) {
5-
const response = await fetch(request);
6-
ctx.waitUntil(
7-
caches.default.put(request, response.clone())
8-
)
9-
ctx.waitUntil(
10-
reportRequestMetric(request, env)
11-
);
12-
return response;
13-
}
4+
async fetch(request, env, ctx, { reportRequestMetric } = { reportRequestMetric }) {
5+
const response = await fetch(request)
6+
ctx.waitUntil(reportRequestMetric(request, env))
7+
return response
8+
},
149
}

lib/influx.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export const reportRequestMetric = async (request, env) => {
1313
* @param {Request} request - incoming request
1414
* @param {object} env - environment variables
1515
*/
16-
const createMetricsFromRequest = (request, env) => {
16+
export const createMetricsFromRequest = (request, env) => {
1717
const url = new URL(request.url);
1818
const timestamp = Date.now();
1919
const apiKey = request.headers.get('api-key') ||
@@ -32,7 +32,7 @@ const createMetricsFromRequest = (request, env) => {
3232
* @param {string} lineProtocolData - InfluxDB line protocol formatted data
3333
* @param {object} env - environment variables
3434
*/
35-
const writeMetrics = async (lineProtocolData, env) => {
35+
export const writeMetrics = async (lineProtocolData, env) => {
3636
// Define API endpoint and headers
3737
const url = `${env.INFLUX_URL}/api/v2/write?&bucket=${env.INFLUX_DATABASE}&precision=ms`;
3838

test/influx.test.js

Lines changed: 61 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,75 +1,96 @@
1-
import { describe, it, expect, vi, beforeEach } from 'vitest';
2-
import { reportRequestMetric } from '../lib/influx.js';
1+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
2+
import { createMetricsFromRequest, writeMetrics } from '../lib/influx.js'
33

4-
describe('reportRequestMetric', () => {
5-
const date = new Date();
6-
const env = {
7-
INFLUX_METRIC_NAME: 'test_metric',
8-
INFLUX_URL: 'https://influx.example.com',
9-
INFLUX_DATABASE: 'test_db',
10-
INFLUX_TOKEN: 'test_token'
11-
};
4+
describe('createMetricsFromRequest', () => {
5+
const date = new Date()
6+
const env = withTestEnvitronment()
127

138
beforeEach(() => {
14-
vi.useFakeTimers();
15-
vi.setSystemTime(date);
16-
global.fetch = vi.fn().mockResolvedValue({ status: 204 });
17-
});
9+
vi.useFakeTimers()
10+
vi.setSystemTime(date)
11+
})
12+
13+
afterEach(() => {
14+
vi.useRealTimers()
15+
})
1816

1917
const testCases = [
2018
{
2119
description: 'when request has an API key in the Authorization header',
2220
request: {
2321
url: 'https://example.com/path',
2422
method: 'GET',
25-
headers: new Map([['Authorization', 'Bearer test-key']])
23+
headers: new Map([['Authorization', 'Bearer test-key']]),
2624
},
27-
expectedApiKey: 'test-key'
25+
expectedApiKey: 'test-key',
2826
},
2927
{
3028
description: 'when request has an API key in the api-key header',
3129
request: {
3230
url: 'https://example.com/path',
3331
method: 'GET',
34-
headers: new Map([['api-key', 'test-key']])
32+
headers: new Map([['api-key', 'test-key']]),
3533
},
36-
expectedApiKey: 'test-key'
34+
expectedApiKey: 'test-key',
3735
},
3836
{
3937
description: 'when request has an API key in the query string',
4038
request: {
4139
url: 'https://example.com/path?api-key=test-key',
4240
method: 'GET',
43-
headers: new Map()
41+
headers: new Map(),
4442
},
45-
expectedApiKey: 'test-key'
43+
expectedApiKey: 'test-key',
4644
},
4745
{
4846
description: 'when request has no API key',
4947
request: {
5048
url: 'https://example.com/path',
5149
method: 'GET',
52-
headers: new Map()
50+
headers: new Map(),
5351
},
54-
expectedApiKey: 'unknown'
55-
}
56-
];
52+
expectedApiKey: 'unknown',
53+
},
54+
]
5755

5856
testCases.forEach(({ description, request, expectedApiKey }) => {
59-
it(description, async () => {
60-
await reportRequestMetric(request, env);
57+
it(description, () => {
58+
const result = createMetricsFromRequest(request, env)
59+
expect(result).toContain(expectedApiKey)
60+
})
61+
})
62+
})
63+
64+
describe('writeMetrics', () => {
65+
it('send request metrics to InfluxDB over HTTP', async () => {
66+
const env = withTestEnvitronment()
67+
const lineProtocolData = 'test_metric api_key="test-key"'
68+
global.fetch = vi
69+
.fn()
70+
.mockResolvedValue(new Response(null, { status: 204 }))
6171

62-
expect(global.fetch).toHaveBeenCalledWith(
63-
'https://influx.example.com/api/v2/write?&bucket=test_db&precision=ms',
64-
expect.objectContaining({
65-
method: 'POST',
66-
headers: expect.objectContaining({
67-
'Authorization': 'Token test_token',
68-
'Content-Type': 'application/octet-stream'
69-
}),
70-
body: `test_metric api_key="${expectedApiKey}" ${date.valueOf()}`
71-
})
72-
);
73-
});
74-
});
75-
});
72+
const response = await writeMetrics(lineProtocolData, env)
73+
74+
expect(global.fetch).toHaveBeenCalledWith(
75+
'https://influx.example.com/api/v2/write?&bucket=test_db&precision=ms',
76+
expect.objectContaining({
77+
method: 'POST',
78+
headers: expect.objectContaining({
79+
Authorization: 'Token test_token',
80+
'Content-Type': 'application/octet-stream',
81+
}),
82+
body: lineProtocolData,
83+
}),
84+
)
85+
expect(response.status).toBe(204)
86+
})
87+
})
88+
89+
const withTestEnvitronment = () => {
90+
return {
91+
INFLUX_METRIC_NAME: 'test_metric',
92+
INFLUX_URL: 'https://influx.example.com',
93+
INFLUX_DATABASE: 'test_db',
94+
INFLUX_TOKEN: 'test_token',
95+
}
96+
}

test/worker.test.js

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,22 @@
1-
import { describe, it, expect, vi } from 'vitest';
21
import worker from '../bin/worker.js';
3-
import { reportRequestMetric } from '../lib/influx.js';
4-
5-
2+
import { describe, it, expect, vi } from 'vitest';
63

74
describe('worker.fetch', () => {
8-
it('should fetch and report metrics correctly', async () => {
5+
it('should fetch and report metrics', async () => {
96
const request = {
10-
url: 'https://example.com/path?api-key=test-key',
7+
url: 'https://example.com/path',
118
method: 'GET'
129
};
13-
const env = {
14-
REQUEST_URL: 'https://proxy.example.com'
15-
};
10+
const env = {};
1611
const ctx = {
1712
waitUntil: vi.fn()
1813
};
19-
20-
global.fetch = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
21-
const response = await worker.fetch(request, env, ctx);
22-
23-
expect(global.fetch).toHaveBeenCalledWith(
24-
expect.objectContaining({
25-
url: 'https://example.com/path?api-key=test-key',
26-
method: 'GET'
27-
})
28-
);
29-
expect(ctx.waitUntil).toHaveBeenCalledWith(reportRequestMetric(request, response, env));
30-
expect(response.status).toBe(200);
14+
global.fetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
15+
const reportRequestMetric = vi.fn()
16+
const response = await worker.fetch(request, env, ctx, { reportRequestMetric });
17+
expect(global.fetch).toHaveBeenCalledWith(request);
18+
expect(ctx.waitUntil).toHaveBeenCalledWith(reportRequestMetric(request, env));
19+
expect(reportRequestMetric).toHaveBeenCalledWith(request, env);
20+
expect(response.status).toBe(204);
3121
});
3222
});

0 commit comments

Comments
 (0)