-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
50 lines (43 loc) · 1.77 KB
/
Copy pathtest.js
File metadata and controls
50 lines (43 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Integration check: 0-floor + CSV round-trip against the real server.
// Run: node test.js (uses a throwaway CSV via the CSV env var)
const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const tmp = path.join(os.tmpdir(), `kc-test-${process.pid}.csv`);
fs.writeFileSync(tmp, 'key,quantity\napples,0\noranges,0\npears,0\n'); // keys come from the CSV
process.env.CSV = tmp;
const PORT = process.env.PORT = '34100'; // avoid clashing with anything on :3000
const base = `http://localhost:${PORT}`;
require('./server');
async function post(key, delta) {
const r = await fetch(`${base}/data`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key, delta }),
});
return (await r.json()).value;
}
const qty = (data, key) => data.find(r => r.key === key).value;
(async () => {
assert.strictEqual(await post('apples', 1), 1);
assert.strictEqual(await post('apples', 1), 2);
assert.strictEqual(await post('apples', -5), 0, 'must floor at 0, not go negative');
// round-trip: value persisted, GET returns the fixed key list with stored qtys
await post('pears', 3);
const data = await (await fetch(`${base}/data`)).json();
assert.deepStrictEqual(data.map(r => r.key), ['apples', 'oranges', 'pears']);
assert.strictEqual(qty(data, 'apples'), 0);
assert.strictEqual(qty(data, 'oranges'), 0);
assert.strictEqual(qty(data, 'pears'), 3);
// unknown key rejected (not in the hardcoded list)
const bad = await fetch(`${base}/data`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'bananas', delta: 1 }),
});
assert.strictEqual(bad.status, 400);
fs.unlinkSync(tmp);
console.log('ok');
process.exit(0);
})();