Skip to content

Commit 913c1b7

Browse files
committed
test: add unit test for TimeWindow
TimeWindow is used by TrackSpendingService for two purposes: - tracking cost within a time window - preventing duplicate alarms within a cooldown period It is important to test this to ensure alarms related to AI costs are accurate.
1 parent 1dad2e8 commit 913c1b7

File tree

2 files changed

+44
-3
lines changed

2 files changed

+44
-3
lines changed

src/backend/src/util/opmath.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -143,16 +143,17 @@ class MovingMode extends StreamReducer {
143143
}
144144

145145
class TimeWindow {
146-
constructor ({ window_duration, reducer }) {
146+
constructor ({ window_duration, reducer, now }) {
147147
this.window_duration = window_duration;
148148
this.reducer = reducer;
149149
this.entries_ = [];
150+
this.now = now ?? Date.now;
150151
}
151152

152153
add (value) {
153154
this.remove_stale_entries_();
154155

155-
const timestamp = Date.now();
156+
const timestamp = this.now();
156157
this.entries_.push({
157158
timestamp,
158159
value,
@@ -174,7 +175,7 @@ class TimeWindow {
174175

175176
remove_stale_entries_ () {
176177
let i = 0;
177-
const current_ts = Date.now();
178+
const current_ts = this.now();
178179
for ( ; i < this.entries_.length ; i++ ) {
179180
const entry = this.entries_[i];
180181
// as soon as an entry is in the window we can break,

src/backend/src/util/opmath.test.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
const { expect } = require('chai');
2+
3+
describe('opmath', () => {
4+
describe('TimeWindow', () => {
5+
it('clears old entries', () => {
6+
const { TimeWindow } = require('./opmath');
7+
let now_value = 0;
8+
const now = () => now_value;
9+
const window = new TimeWindow({ window_duration: 1000, now });
10+
11+
window.add(1);
12+
window.add(2);
13+
window.add(3);
14+
15+
now_value = 900;
16+
17+
window.add(4);
18+
window.add(5);
19+
window.add(6);
20+
21+
expect(window.get()).to.deep.equal([1, 2, 3, 4, 5, 6]);
22+
23+
now_value = 1100;
24+
25+
window.add(7);
26+
window.add(8);
27+
window.add(9);
28+
29+
expect(window.get()).to.deep.equal([4, 5, 6, 7, 8, 9]);
30+
31+
now_value = 2000;
32+
33+
expect(window.get()).to.deep.equal([7, 8, 9]);
34+
35+
now_value = 2200;
36+
37+
expect(window.get()).to.deep.equal([]);
38+
})
39+
})
40+
});

0 commit comments

Comments
 (0)