Skip to content

Commit 039906a

Browse files
committed
Add unit tests
1 parent 14f5cf5 commit 039906a

File tree

2 files changed

+110
-0
lines changed

2 files changed

+110
-0
lines changed

library/agent/context/user.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,3 +188,16 @@ t.test("it sets user with rateLimitGroup", async (t) => {
188188
});
189189
});
190190
});
191+
192+
t.test("it sets user with rateLimitGroup (number)", async (t) => {
193+
const context = createContext();
194+
195+
runWithContext(context, () => {
196+
setUser({ id: "id", name: "name", rateLimitGroup: 1 });
197+
t.same(getContext()?.user, {
198+
id: "id",
199+
name: "name",
200+
rateLimitGroup: "1",
201+
});
202+
});
203+
});

library/sources/graphql/shouldRateLimitOperation.test.ts

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,3 +172,100 @@ t.test("it rate limits mutation", async () => {
172172
block: true,
173173
});
174174
});
175+
176+
t.test("it rate limits user groups", async () => {
177+
const agent = createTestAgent({
178+
token: new Token("123"),
179+
api: new ReportingAPIForTesting({
180+
success: true,
181+
endpoints: [
182+
{
183+
method: "POST",
184+
route: "/graphql",
185+
forceProtectionOff: false,
186+
rateLimiting: {
187+
enabled: true,
188+
maxRequests: 3,
189+
windowSizeInMS: 60 * 1000,
190+
},
191+
graphql: {
192+
name: "signup",
193+
type: "mutation",
194+
},
195+
},
196+
],
197+
allowedIPAddresses: [],
198+
configUpdatedAt: 0,
199+
heartbeatIntervalInMS: 10 * 60 * 1000,
200+
blockedUserIds: [],
201+
}),
202+
});
203+
204+
agent.start([]);
205+
await new Promise((resolve) => setTimeout(resolve, 0));
206+
207+
const args: Args = {
208+
document: parse(`
209+
mutation signup {
210+
signup(input: { email: "john@acme.come" }) {
211+
id
212+
}
213+
}
214+
`),
215+
};
216+
217+
const getContext = (
218+
ip: string,
219+
userId: string,
220+
groupId: string
221+
): Context => ({
222+
remoteAddress: ip,
223+
method: "POST",
224+
url: "http://localhost:4000",
225+
query: {},
226+
headers: {},
227+
body: undefined,
228+
cookies: {},
229+
routeParams: {},
230+
source: "express",
231+
route: "/graphql",
232+
user: {
233+
id: userId,
234+
rateLimitGroup: groupId,
235+
},
236+
});
237+
238+
for (let i = 0; i < 3; i++) {
239+
t.same(
240+
shouldRateLimitOperation(
241+
agent,
242+
getContext(`192.1.2.${i}`, i.toString(), "group1"),
243+
args
244+
),
245+
{
246+
block: false,
247+
}
248+
);
249+
}
250+
251+
t.match(
252+
shouldRateLimitOperation(
253+
agent,
254+
getContext("192.1.2.22", "123456", "group1"),
255+
args
256+
),
257+
{
258+
block: true,
259+
}
260+
);
261+
t.match(
262+
shouldRateLimitOperation(
263+
agent,
264+
getContext("192.1.2.24", "123456", "group2"),
265+
args
266+
),
267+
{
268+
block: false,
269+
}
270+
);
271+
});

0 commit comments

Comments
 (0)